[英]Pivot table Q - SQL Server 2008
I have the following table ... 我有下表...
GROUPING Num DEF TOTAL SOURCE
a 1 a -2503 WTH
a 2 b -180 DET
a 2 c -156 PLY
a 4 d -99 DET
a 5 e -252 DET
Which I'd like to present as follows ... 我想介绍如下...
GROUPING Num DET PLY WTH
a 1 -2503
a 2 -180 -156
a 4 -99
a 5 -252
Here is my effort ... 这是我的努力...
select
grouping
,num
,det
,ply
,wth
from #temp
pivot (
sum([TOTAL]) for [SOURCE] in (det,ply,wth)
) x
But I get 2 rows with num = 2 where I want 1 row. 但是我得到2行,其中num = 2,我想要1行。
Any help appreciated. 任何帮助表示赞赏。
Thanks, James 谢谢,詹姆斯
Your existing query is not using a subquery to select from your table, as a result all of the columns not used by the PIVOT are used in the GROUP BY
. 您现有的查询未使用子查询从表中进行选择,因此PIVOT未使用的所有列都在GROUP BY
。 Since you have multiple distinct values for the DEF
column you are returning multiple rows for num=2
. 由于DEF
列具有多个不同的值,因此将返回num=2
多行。
I would use a subquery to select only the columns you need for the PIVOT and the final select list: 我将使用子查询来仅选择PIVOT所需的列和最终的选择列表:
select
grouping
,num
,det
,ply
,wth
from
(
select grouping, num, total, source
from #temp
) d
pivot
(
sum([TOTAL])
for [SOURCE] in (det,ply,wth)
) x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.