如何在mysql中通过查询获取组上的第一个值?

问题描述 投票:0回答:1

我有一个 mysql 表,其中包含 id、llaveord、nomb、imp。

记录与相同的 llaveord 成对出现,例如:

id llaveord 名字 小鬼
1 啊啊啊 一些1 100
2 啊啊啊 xxx 50
3 bbbb 一些2 110
4 bbbb xxx 50
5 cccc 一些3 70
6 cccc xxx 50

我需要得到这个:

llaveord 名字 总和
啊啊啊 一些1 150
bbbb 一些2 160
cccc 一些3 120

但是按查询进行常规分组显示了这一点:

llaveord 名字 总和
啊啊啊 xxx 150
bbbb xxx 160
cccc xxx 120

知道如何获得第一个而不是最后一个吗?

蒂亚

mysql
1个回答
0
投票

您可以在此处使用加窗函数来获得所需的结果。根据需要调整

rn
的订购标准。

select llaveord, nomb, sum 
from (
  select *, 
    Sum(imp) over(partition by llaveord) sum, 
    Row_Number() over (partition by llaveord order by imp desc) rn 
  from t
)t
where rn = 1;

示例小提琴

© www.soinside.com 2019 - 2024. All rights reserved.