如何在SQl Pivot查询中进行求和操作

时间:2017-05-02 08:40:22

标签: sql sql-server

这里我有一个简单的表Name Cust with CustName,PurshaseItem,Price.I写了一个简单的PIVOT查询它透视数据但是我想显示amot的总和 在这里,我需要总计

透视查询

[![select custName,

       \[Shoes\] as Shoes,
       \[Colgate\] as Colgate,
       \[Cloths\] as Cloths

FROM
(select custName,Price,PurchaseItem FROM Cust
) AS PIVOTData

PIVOT(
sum(Price) FOR PurchaseItem 
IN (Shoes,Colgate,Cloths)
)AS PIVOTING][1]][1]


custname       Shoes    Colgate       GrandTotal
xyz           12         10           22
lmn            1          2            3

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

CREATE TABLE CUST (custName VARCHAR(10),
       price INT,
       PurchaseItem VARCHAR(10)
       )
       INSERT INTO CUST VALUES ('aaaa', 1,'Colgate')
       INSERT INTO CUST VALUES ('aaaa', 2,'Shoes')
       INSERT INTO CUST VALUES ('aaaa', 3,'Cloths')
       INSERT INTO CUST VALUES ('bbbb', 4,'Colgate')
       INSERT INTO CUST VALUES ('bbbb', 5,'Shoes')
       INSERT INTO CUST VALUES ('bbbb', 6,'Cloths')


select *
FROM
(select custName, SUM(Price)   AS Price ,
     CASE WHEN GROUPING(PurchaseItem)=1 THEN 'TOT_PRICE' ELSE PurchaseItem END AS PurchaseItem
  FROM Cust
  group by rollup(PurchaseItem), custName
) AS PIVOTData

PIVOT(sum(Price) FOR PurchaseItem IN (Shoes,Colgate,Cloths,TOT_PRICE)) AS PIVOTING

输出:

custName   Shoes       Colgate     Cloths      TOT_PRICE
---------- ----------- ----------- ----------- -----------
aaaa       2           1           3           6
bbbb       5           4           6           15

答案 1 :(得分:1)

您可以将其添加到您的选择

coalesce([Shoes], 0) + coalesce([Colgate], 0) + coalesce([Cloths], 0) as GranTotal

当其中一个结果为coalesce时,需要null来避免奇怪的行为。