我正在尝试旋转表格并且遇到了一些困难。我的表架构如下所示:
ID W_C W_P A_C A_P
3 257 251342 217 206078
4 443 109023 332 87437
6 17 9985 32 13515
我想要完成的事情是:
3 4 6
w_c 257 443 17
w_p 251342 109023 9985
a_c 217 332 87437
a_p 206078 87437 13515
我不需要显示w_c
, w_p
, a_c
, 或者a_p
我只是将它用作参考点。
我认为可能有一种使用 pivot/unpivot 的方法,但我对它们不是很熟悉,而且我读过的内容对我没有帮助。
我尝试使用 CTE 做一些事情,但我认为它过于复杂并且是不好的做法:
;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 已经创建了表:http ://sqlfiddle.com/#!3/02ef2/6