[英]Pivoting a SQL table
InvoiceDocValue OppoFWDocID dtadded ddQuarter
184046.19 166262 2016-01-04 16:09:06.000 1
31047.05 166262 2016-05-06 13:50:47.000 2
5160.00 169328 2016-09-08 13:39:35.000 3
59931.48 169987 2016-10-07 14:11:33.000 4
98989.9 166345 2016-02-07 15:09:34.000 1
76543.9 189873 2016-02-07 05:07:54.000 1
I would like to add this Pivot this table so the columns should be:我想添加这个 Pivot 这个表,所以列应该是:
OppoFWDocID 1 2 3 4
166262 184046.19 31047.05 0 0
169987 0 0 0 59931.48
169328 0 0 5160.00 0
166345 98989.9 0 0 0
189873 76543.9 0 0 0
Columns 1,2,3 and 4 should show the sum of all the InvoiceDocValue
for that Quarter.第 1、2、3 和 4 列应显示该季度所有InvoiceDocValue
的总和。
You can use the below query:您可以使用以下查询:
SELECT (T.OppoFWDocID) OppoFWDocID,
SUM(DECODE(T.ddQuarter,1,T.InvoiceDocValue)) 1,
SUM(DECODE(T.ddQuarter,2,T.InvoiceDocValue)) 2,
SUM(DECODE(T.ddQuarter,3,T.InvoiceDocValue)) 3,
SUM(DECODE(T.ddQuarter,4,T.InvoiceDocValue)) 4
FROM table_name T
GROUP BY T.OppoFWDocID
Use Case:用例:
select OppoFWDocID
case when ddQuarter =1 then InvoiceDocValue end as 1,
case when ddQuarter =2 then InvoiceDocValue end as 2,
...
group by OppoFWDocID
Assuming you have a fixed number of columns, you can use SUM , CASE , and GROUP BY .假设您有固定数量的列,您可以使用SUM 、 CASE和GROUP BY 。
SELECT OppoFWDocID
,SUM(CASE WHEN ddQuarter = '1' THEN InvoiceDocValue ELSE 0 END) AS '1'
,SUM(CASE WHEN ddQuarter = '2' THEN InvoiceDocValue ELSE 0 END) AS '2'
,SUM(CASE WHEN ddQuarter = '3' THEN InvoiceDocValue ELSE 0 END) AS '3'
,SUM(CASE WHEN ddQuarter = '4' THEN InvoiceDocValue ELSE 0 END) AS '4'
FROM #TABLE GROUP BY OppoFWDocID
You can go for PIVOT operator as given below:您可以使用 PIVOT 运算符,如下所示:
DECLARE @table table(InvoiceDocValue float, OppoFWDocID int, dtadded datetime, ddQuarter int)
insert into @table values
(184046.19 ,166262 ,'2016-01-04 16:09:06.000', 1),
(31047.05 ,166262 ,'2016-05-06 13:50:47.000', 2),
(5160.00 ,169328 ,'2016-09-08 13:39:35.000', 3),
(59931.48 ,169987 ,'2016-10-07 14:11:33.000', 4),
(98989.9 ,166345 ,'2016-02-07 15:09:34.000', 1),
(76543.9 ,189873 ,'2016-02-07 05:07:54.000', 1);
SELECT OppoFWDocID, ISNULL([1],0) as [1], ISNULL([2],0) as [2],ISNULL([3],0) as [3], ISNULL([4],0) as [4]
FROM (SELECT InvoiceDocValue, OppoFWDocID, ddQuarter from @table) as t
pivot (sum(InvoiceDocValue) FOR ddQuarter in ([1],[2],[3],[4])) as pvt
OppoFWDocID OppoFWDocID | 1 1 | 2 2 | 3 3 | 4 4 |
---|---|---|---|---|
166262 166262 | 184046.19 184046.19 | 31047.05 31047.05 | 0 0 | 0 0 |
166345 166345 | 98989.9 98989.9 | 0 0 | 0 0 | 0 0 |
169328 169328 | 0 0 | 0 0 | 5160 5160 | 0 0 |
169987 169987 | 0 0 | 0 0 | 0 0 | 59931.48 59931.48 |
189873 189873 | 76543.9 76543.9 | 0 0 | 0 0 | 0 0 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.