首页 > 解决方案 > SQL Server Pivot - 无法按列添加

问题描述

我通常不使用数据透视表和修复存储过程。我认为问题在于枢轴声明。

我有下表:

#status_totals
ProductName  Orders Status
-------------------------------
Product1     1      inprogress
Product1     1      inprogress
Product1     1      ordered
Product1     1      ordered
Product1     1      inprogress

这是我正在使用的 sql 语句。

select ProductName, ordered
from #status_totals
pivot (SUM(Orders) for Status in ([ordered])) as StatusTotals

这是结果

ProductName  ordered    
---------------------
Product1     NULL       
Product1     NULL       
Product1     1          
Product1     1          
Product1     NULL   

这不是我要找的。我应该有一条线

ProductName  ordered    
---------------------
Product1     2

不知道如何得到我想要的结果。

标签: sqlsql-server

解决方案


我会使用条件聚合函数 CASE WHEN来做sum数据透视。

CREATE TABLE T(
  ProductName varchar(50),
  Orders int,
  Status varchar(50)
);



INSERT INTO T VALUES ('Product1',1,'inprogress');
INSERT INTO T VALUES ('Product1',1,'inprogress');
INSERT INTO T VALUES ('Product1',1,'ordered');
INSERT INTO T VALUES ('Product1',1,'ordered');
INSERT INTO T VALUES ('Product1',1,'inprogress');

查询 1

SELECT ProductName  ,SUM(CASE WHEN Status = 'ordered' THEN Orders END) ordered
FROM T
GROUP BY ProductName  

结果

| ProductName | ordered |
|-------------|---------|
|    Product1 |       2 |

推荐阅读