SQL:选择前3个记录+数量总和

时间:2013-08-01 04:53:30

标签: sql sql-server count

我想显示现有订单表中的前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

2 个答案:

答案 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

SQL Fiddle Demo