[英]SQL Query to obtain the maximum value for each unique value in another column
ID Sum Name
a 10 Joe
a 8 Mary
b 21 Kate
b 110 Casey
b 67 Pierce
What would you recommend as the best way to obtain for each ID the name that corresponds to the largest sum (grouping by ID). 您会建议什么是最好的方法,以使每个ID获得对应于最大和的名称(按ID分组)。 What I tried so far:
到目前为止我尝试过的是:
select ID, SUM(Sum) s, Name
from Table1
group by ID, Name
Order by SUM(Sum) DESC;
this will arrange the records into groups that have the highest sum first. 这会将记录排在总和最高的组中。 Then I have to somehow flag those records and keep only those.
然后我必须以某种方式标记这些记录并仅保留这些记录。 Any tips or pointers?
有任何提示或指示吗? Thanks a lot
非常感谢
In the end I'd like to obtain: 最后,我想获得:
a 10 Joe
b 110 Casey
You want the row_number()
function: 您需要
row_number()
函数:
select id, [sum], name
from (select t.*]
row_number() over (partition by id order by [sum] desc) as seqnum
from table1
) t
where seqnum = 1;
Your question is more confusing than it needs to be because you have a column called sum
. 您的问题比需要的要混乱的多,因为您有一列称为
sum
的列。 You should avoid using SQL reserved words for identifiers. 您应该避免使用SQL保留字作为标识符。
The row_number()
function assigns a sequential number to a group of rows, starting with 1. The group is defined by the partition by
clause. row_number()
函数将顺序号分配给从1开始的一组行。该组由partition by
子句定义。 In this case, all rows with the same id
are in the same group. 在这种情况下,具有相同
id
所有行都在同一组中。 The ordering of the numbers is determined by the order by
clause, so the one with the largest value of sum
gets the value of 1
. 数字的排序由
order by
子句确定,因此sum
的最大值最大的sum
为1
。
If you might have duplicate maximum values and you want all of them, use the related function rank()
or dense_rank()
. 如果您可能有重复的最大值并且想要所有最大值,请使用相关的函数
rank()
或dense_rank()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.