5

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

2 回答 2

8

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
于 2013-08-01T04:58:11.150 回答
7
SELECT TOP 3 ProductID, SUM(Quantity) as SUMQUANTITY
FROM Table1
GROUP BY ProductID
ORDER BY SUMQUANTITY desc

SQL 小提琴演示

于 2013-08-01T05:00:15.790 回答