sql - 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
不知道如何得到我想要的结果。
解决方案
我会使用条件聚合函数
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 |
推荐阅读
- excel - 优化座位表
- python - 如何在 Discord 中更新 message.content 中的每条新消息?
- python - 如何使用 Pandas 计算每个组合的计数
- push-notification - 基于 Kafka 的通知引擎,用于向 Android 和 iOS 应用程序发送推送通知
- python-3.x - 使用 scipy.optimize 和“SLSQP”方法时,最终结果保持在初始值
- python - error importing installed python packages in nodejs pyshell
- ios - 如果我们可以只检查收据,那么检查交易队列有什么意义?
- c++ - 屏幕上字符的“宽度”
- javascript - VueJS:需要在重新加载页面之前清除浏览器缓存
- xcode - Safari iphone模拟器调试不起作用