希望我能正确解释这一点。我有一个行订单表(每个行订单由商品数量和价格组成,还有其他字段,但我忽略了这些字段。)
表“orderitems”:
orderid | quantity | price
1 | 1 | 1.5000
1 | 2 | 3.22
2 | 1 | 9.99
3 | 4 | 0.44
3 | 2 | 15.99
因此,为了获得订单总数,我会运行
SELECT SUM(Quantity * price) AS total
FROM OrderItems
GROUP BY OrderID
但是,我想获取 1 美元以下的所有订单总额的计数(只需提供计数)。
我希望最终结果能够定义范围: 低于 1 美元、1 美元 - 3 美元、3-5、5-10、10-15、15.. 等;
我的数据看起来像这样(希望如此):
tunder1 | t1to3 | t3to5 | t5to10 | etc
10 | 500 | 123 | 5633 |
这样我就可以在我们的电子商务网站上展示客户订单的饼图分割。 现在我可以运行单独的 SQL 查询来获取此信息,但我想知道最有效的“单个 sql 查询”是什么。我正在使用 MS SQL Server。
目前,我可以像这样运行单个查询,以获得总计不到 1 美元的费用:
SELECT COUNT(total) AS tunder1
FROM (SELECT SUM(Quantity * price) AS total
FROM OrderItems
GROUP BY OrderID) AS a
WHERE (total < 1)
我该如何优化这个?提前致谢!
最佳答案
select
count(case when total < 1 then 1 end) tunder1,
count(case when total >= 1 and total < 3 then 1 end) t1to3,
count(case when total >= 3 and total < 5 then 1 end) t3to5,
...
from
(
select sum(quantity * price) as total
from orderitems group by orderid
);
关于sql - 生成按订单总数分组的订单统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2343155/