Sql 将行透视到列
我正在试着旋转一张桌子,有点困难。我的表架构如下所示:Sql 将行透视到列,sql,tsql,sql-server-2005,pivot,unpivot,Sql,Tsql,Sql Server 2005,Pivot,Unpivot,我正在试着旋转一张桌子,有点困难。我的表架构如下所示: 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
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摆弄已创建的表:您可以先使用and,然后使用a来获得所需的结果(请参阅):
在此查询中,您将首先,
UNPIVOT
,这将使您更容易访问要转换的数据。您可以为值
和列
字段使用您想要的任何名称,我只是在本例中选择了这个名称。一旦数据被取消激活,您就可以应用一个透视
,以获得最终产品。@Brad很乐意提供帮助,需要记住的一点是,如果您有很多列,您也可以将其作为动态查询编写
select col, [3], [4], [6]
from
(
select id, value, col
from
(
select id, w_c, w_p, a_c, a_p
from t
) x
unpivot
(
value
for col in (w_c, w_p, a_c, a_p)
)u
) x1
pivot
(
sum(value)
for id in ([3], [4], [6])
) p