![](/img/trans.png)
[英]Query to obtain the maximum primary key ID of a table for each unique value of the customerID column in the same table
[英]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
您会建议什么是最好的方法,以使每个ID获得对应于最大和的名称(按ID分组)。 到目前为止我尝试过的是:
select ID, SUM(Sum) s, Name
from Table1
group by ID, Name
Order by SUM(Sum) DESC;
这会将记录排在总和最高的组中。 然后我必须以某种方式标记这些记录并仅保留这些记录。 有任何提示或指示吗? 非常感谢
最后,我想获得:
a 10 Joe
b 110 Casey
您需要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;
您的问题比需要的要混乱的多,因为您有一列称为sum
的列。 您应该避免使用SQL保留字作为标识符。
row_number()
函数将顺序号分配给从1开始的一组行。该组由partition by
子句定义。 在这种情况下,具有相同id
所有行都在同一组中。 数字的排序由order by
子句确定,因此sum
的最大值最大的sum
为1
。
如果您可能有重复的最大值并且想要所有最大值,请使用相关的函数rank()
或dense_rank()
。
select *
from
(
select *
,rn = row_number() over (partition by Id order by sum desc)
from table
)x
where x.rn=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.