SQL Server Pivot-Can';不按列添加

SQL Server Pivot-Can';不按列添加,sql,sql-server,Sql,Sql Server,我通常不使用透视表和修复存储过程。我认为问题在于核心陈述 我有下表: #status_totals ProductName Orders Status ------------------------------- Product1 1 inprogress Product1 1 inprogress Product1 1 ordered Product1 1 ordered Product1 1 inp

我通常不使用透视表和修复存储过程。我认为问题在于核心陈述

我有下表:

#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

不确定如何获得我想要的结果。

我将使用条件聚合函数,
使用
求和
进行旋转时的情况

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 |

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

没有必要使用
PIVOT
为此,您应该使用一个简单的
CASE
表达式和
SUM

SELECT ProductName, 
       SUM(CASE WHEN [Status] = 'ordered' THEN Orders END) Ordered
FROM #status_totals
GROUP BY ProductName;
修复那个支点? 然后它看起来像这样:

SELECT *
FROM
(
    SELECT ProductName, Orders, Status
    FROM #status_totals
    WHERE Status IN ('ordered')
) AS src
PIVOT 
(
   SUM(Orders) FOR Status IN ([ordered])
) AS pvt;
但是要得到预期的结果呢?
这已经足够了:

SELECT ProductName, SUM(Orders) AS [ordered]
FROM #status_totals
WHERE Status = 'ordered'
GROUP BY ProductName
ORDER BY ProductName;