示例表订单
+---------+----------+ | OrderID | Quantity | +---------+----------+ | 10248 | 11 | | 10248 | 42 | | 10248 | 72 | | 10249 | 14 | | 10249 | 51 | | 10250 | 41 | | 10250 | 51 | +---------+----------+
我的问题是。 如何查找每个orderid的数量总和并按订单查找最高数量
<select orderid , SUM(quantity) As TotalQty from order group by orderid
结果
+--------+-----------+ |orderId | TotalQTY | +--------+-----------+ | 10248 | 125 | | 10249 | 65 | | 10250 | 92 | +--------+-----------+
从上面的结果我需要显示总数最高的orderid。
最终结果必须是
+--------+----------+ |orderid | TotalQTY | +--------+----------+ | 10245 | 125 | +--------+----------+
我在一个查询中需要这个
答案 0 :(得分:6)
在MySQL中使用
select orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by TotalQty desc
limit 1
在MSSQL中
select top 1 orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by SUM(quantity) desc
在Oracle中
select orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by SUM(quantity) desc
where ROWNUM <= 1
答案 1 :(得分:2)
如果是SQL-Server,您可以使用OVER
clause:
SELECT TOP 1 orderid, SUM(Quantity)OVER(PARTITION BY orderid)AS TotalQTY
FROM dbo.Orders
ORDER BY TotalQTY DESC
您可以包含所有列,即使它们未汇总或属于GROUP BY
。
答案 2 :(得分:0)
Oracle:
select * from (
select orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by TotalQty desc) where rownum =1;
答案 3 :(得分:0)
MySQL的:
select orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by TotalQty desc
limit 1
答案 4 :(得分:0)
with cte IN SQL SERVER
;with cte as
(
select top 1 orderid,sum(TotalQTY) as x from table group by id
)
select * from cte
OPTION (MAXRECURSION 1);