0
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

4 回答 4

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
于 2016-10-07T16:04:55.287 回答
0

用例:

select OppoFWDocID 

case when ddQuarter  =1 then InvoiceDocValue end as 1,
case when ddQuarter  =2 then InvoiceDocValue end as 2,
...
group by OppoFWDocID 
于 2016-10-07T15:41:47.570 回答
0

假设您有固定数量的列,您可以使用SUMCASEGROUP 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
于 2016-10-07T15:57:26.627 回答
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
于 2021-07-01T10:14:07.520 回答