SQL:选择前3条记录+数量总和 [英] SQL: Select Top 3 Records + Sum of Quantity
本文介绍了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
$ b b
预期输出
Expected Output
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
这篇关于SQL:选择前3条记录+数量总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文