gpt4 book ai didi

sql - 根据另一列的总和选择列

转载 作者:行者123 更新时间:2023-12-04 15:27:19 26 4
gpt4 key购买 nike

假设我有

SalesManagerId, SaleAmount, ProductId

我要总结 SaleAmount对于每个( SalesManagerIdProductId )并获取 ProductId最大 sum(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com