这是我的基本查询(SQL Server):
SELECT projectID, businessID, sum(number) AS summ
FROM table
GROUP BY projectID, businessID
ORDER BY projectID, sum(number) DESC
它产生一个像这样的表:
Project ID Business ID Summ
1 1 63
1 2 32
1 3 6
2 3 45
2 1 44
2 2 3
我想要获取每个项目ID的Summ列最大的项目ID和业务ID。因此,在给定的示例中,第1行和第4行。如何调整原始查询以执行此操作?
最佳答案
您可以使用分析功能:
SELECT projectID,
businessID,
summ
FROM(SELECT projectID,
businessID,
SUM(number) AS summ,
ROW_NUMBER() OVER (PARTITION BY projectID
ORDER BY SUM(number) DESC) AS rn
FROM table
GROUP
BY projectID,
businessID
) t
WHERE rn = 1
ORDER
BY projectID;
希望有帮助。
关于sql - SQL选择行,其中列的总和最大(GROUP BY中有两个字段),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29991767/