透视SQL表

时间:2016-10-07 15:35:42

标签: sql sql-server sql-query-store

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

我想在此表中添加此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

第1,2,3和4列应显示该季度的所有InvoiceDocValue的总和。

4 个答案:

答案 0 :(得分:1)

嗨,您可以使用以下查询

 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

答案 1 :(得分:0)

用例:

select OppoFWDocID 

case when ddQuarter  =1 then InvoiceDocValue end as 1,
case when ddQuarter  =2 then InvoiceDocValue end as 2,
...
group by OppoFWDocID 

答案 2 :(得分:0)

假设您有固定数量的列,您可以使用 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

答案 3 :(得分:0)

您可以使用如下所示的 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 1 2 3 4
166262 184046.19 31047.05 0 0
166345 98989.9 0 0 0
169328 0 0 5160 0
169987 0 0 0 59931.48
189873 76543.9 0 0 0