假设我有

SalesManagerId, SaleAmount, ProductId

我想总结每个SaleAmount(SalesManagerIdProductId),并获取最大ProductIdsum(SaleAmount)

一个查询有可能吗?

例子:
1, 100, 1
1, 200, 1
1, 600, 1
1, 400, 2
2, 100, 3
3, 100, 4
3, 100, 4
2, 500, 6
3, 100, 5

结果:
1, 900, 1
2, 500, 6
3, 200, 4

最佳答案

如果您有可用的分析功能,则可以使用RANK()
就像是:

SELECT SalesManagerId, ProductId, Total
FROM (
  SELECT SalesManagerId,
         ProductId,
         SUM(SaleAmount) as Total,
         RANK() OVER(PARTITION BY SalesManagerId
                     ORDER BY SUM(SaleAmount) DESC) as R
  FROM <Table name>
  GROUP BY SalesManagerId, ProductId) as InnerQuery
WHERE InnerQuery.R = 1

关于sql - 根据另一列的总和选择列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4109622/

10-15 16:00