我想显示现有订单表中的前3个记录。为了实现这一目标,我需要计算每个产品数量的总和。
现有记录:
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
答案 0 :(得分:8)
您需要SUM
然后ORDER BY
此汇总值:
SELECT TOP 3 ProductID, SUM(Quantity) as qSum
FROM Table
GROUP BY ProductID
ORDER BY qSum DESC
答案 1 :(得分:7)
SELECT TOP 3 ProductID, SUM(Quantity) as SUMQUANTITY
FROM Table1
GROUP BY ProductID
ORDER BY SUMQUANTITY desc