I am trying to pivot a table and am having a bit of difficulty. My table schema looks like this:
ID W_C W_P A_C A_P
3 257 251342 217 206078
4 443 109023 332 87437
6 17 9985 32 13515
What I am trying to accomplish is something to the effect of:
3 4 6
w_c 257 443 17
w_p 251342 109023 9985
a_c 217 332 87437
a_p 206078 87437 13515
I do not need to display the w_c, w_p, a_c, or a_p I just was using it as a point of reference.
I think there may be a way of doing it with pivot/unpivot but I am not very familiar with them, and what I have read isn’t helping me.
I tried doing something using CTE’s but I believe it is overly complicated and is just bad practice:
;with [3_Data] as (
Select
1 as [common_key3]
,max(Case when [id] = 3 then [w_c] else 0 end) as [3_Records]
From [example]
), [4_data] as (
Select
1 as [common_key4]
,max(Case when [id] = 4 then [w_c] else 0 end) as [4_Records]
From [example]
), [6_data] as (
Select
1 as [common_key6]
,max(Case when [id] = 6 then [w_c] else 0 end) as [6_Records]
From [example]
)
Select [3_Records], [4_Records], [6_Records]
From [3_Data]
inner join [4_data] on [common_key3] = [common_key4]
inner join [6_data] on [common_key3] = [common_key6]
Sql fiddle with table already created: http://sqlfiddle.com/#!3/02ef2/6
You can use an
UNPIVOTand then aPIVOTto get the result you want (See SQL Fiddle with Demo):In this query you will first,
UNPIVOTwhich will allow you easier access to the data to transform. You can use whatever names you want for thevalueandcolfields, I just chose that for this example. Once the data is unpivoted, you can then apply aPIVOTto get the final product.