如何在单个查询中组合SUM和MAX?
假设我有一个订单规则:
ProductID \ Quantity
我可以说:
Select ProductID,SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
ORDER BY SUM(Quantity) Desc
然而,这将返回所有销售,而不仅仅是最畅销的产品(数量)。
答案 0 :(得分:2)
试试这个
SELECT TOP(1)
*
FROM
(
Select
ProductID,
MAX(Quantity) As MaxQuantity,
SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
)AS X
ORDER BY Sold DESC
答案 1 :(得分:1)
SELECT TOP 1 ProductID, Sold FROM
(
SELECT ProductID, SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
) totals
ORDER BY Sold DESC
答案 2 :(得分:1)
所以有两种方法可以做到 - 首先要限制结果数量,例如:
select * from (your_select) where rownum = 1
另一个是选择具有最高值的那个,这将需要一个子选择,如:
having sum(quantity) =
(select max(sum_quan) from (select sum(Quantity) from orderrule group by Product_id))