-3

示例表订单

+---------+----------+
| 订单号 | 数量 |
+---------+----------+
| 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

结果

+--------+------------+
|订单号 | 总数量 |
+--------+------------+
| 10248 | 125 |
| 10249 | 65 |
| 10250 | 92 |
+--------+------------+

从上面的结果中,我需要显示总数最高的 orderid。

最终结果必须是

+--------+----------+
|订单号 | 总数量 |
+--------+----------+
| 10245 | 125 |
+--------+----------+

我在一个查询中需要这个

4

5 回答 5

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

在甲骨文中

select orderid, SUM(quantity) As TotalQty
from order 
group by orderid
order by SUM(quantity) desc
where ROWNUM <= 1
于 2013-11-15T09:57:08.890 回答
2

在 SQL-Server 的情况下,您可以使用以下OVER子句

SELECT TOP 1 orderid, SUM(Quantity)OVER(PARTITION BY orderid)AS TotalQTY
FROM dbo.Orders
ORDER BY TotalQTY DESC

Demo

您可以包括所有列,即使它们不是聚合的或不属于GROUP BY.

于 2013-11-15T10:01:33.157 回答
0

甲骨文:

select * from (
select orderid, SUM(quantity) As TotalQty
from order
group by orderid
order by TotalQty desc) where rownum =1;
于 2013-11-15T09:59:24.373 回答
0

mysql:

select orderid, SUM(quantity) As TotalQty
from order 
group by orderid
order by TotalQty desc
limit 1
于 2013-11-15T09:59:45.927 回答
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);
于 2013-11-15T10:12:19.340 回答