希望我能正确地解释这一点。我有一个行订单表(每个行订单由项目数量和价格组成,还有其他字段,但我省略了这些字段)。
表‘orderitem’:
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 |这样我就可以在我们的eCommerce站点上显示客户订单的分段分解。现在我可以运行单独的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)我如何优化这一点?提前感谢!
发布于 2010-02-27 00:42:56
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
);发布于 2010-02-27 00:43:10
您需要使用HAVING来过滤分组值。
发布于 2010-02-27 00:51:06
试试这个:
DECLARE @YourTable table (OrderID int, Quantity int, Price decimal)
INSERT INTO @YourTable VALUES (1,1,1.5000)
INSERT INTO @YourTable VALUES (1,2,3.22)
INSERT INTO @YourTable VALUES (2,1,9.99)
INSERT INTO @YourTable VALUES (3,4,0.44)
INSERT INTO @YourTable VALUES (3,2,15.99)
SELECT
SUM(CASE WHEN TotalCost<1 THEN 1 ELSE 0 END) AS tunder1
,SUM(CASE WHEN TotalCost>=1 AND TotalCost<3 THEN 1 ELSE 0 END) AS t1to3
,SUM(CASE WHEN TotalCost>=3 AND TotalCost<5 THEN 1 ELSE 0 END) AS t3to5
,SUM(CASE WHEN TotalCost>=5 THEN 1 ELSE 0 END) AS t5andup
FROM (SELECT
SUM(quantity * price) AS TotalCost
FROM @YourTable
GROUP BY OrderID
) dt输出:
tunder1 t1to3 t3to5 t5andup
----------- ----------- ----------- -----------
0 0 0 3
(1 row(s) affected)https://stackoverflow.com/questions/2343155
复制相似问题