SQL:选择前 3 条记录 + 数量总和
我想显示现有订单表中的前 3 条记录.为了实现这一点,我需要计算每个产品的数量总和.
I would like to display the top 3 records from the existing Orders table. In order to accomplish this, I need to calculate the sum of each product's quantity.
现有记录:
OrderNo ProductID Quantity
1 1 50
1 2 30
1 3 20
2 2 30
3 1 100
3 4 50
4 1 20
4 5 10
5 2 10
预期输出
ProductID Quantity
1 170
2 70
4 50
推荐答案
你需要SUM
然后ORDER BY
这个汇总值:
You need to SUM
and then ORDER BY
this summary value:
SELECT TOP 3 ProductID, SUM(Quantity) as qSum
FROM Table
GROUP BY ProductID
ORDER BY qSum DESC
相关文章