如何在SQL中为每个具有行号的用户id选择最大收入?

如何在SQL中为每个具有行号的用户id选择最大收入?,sql,Sql,在我的数据集中,有一些用户id,每个用户id都有多个行号(从1到n),每一行都有特定的收入。我想为每个用户_id选择行号属于此收入的最大收入。我想查询突出显示的行的结果 一种方法是相关子查询: select t.* from t where t.revenue = (select max(t2.revenue) from t t2 where t2.user_id = t.user_id); 如果最大值有关联,则返回所有最大值行。用您正在使用的数据库标记您的问题。谢谢,这是什么tm?我尝试了您

在我的数据集中,有一些用户id,每个用户id都有多个行号(从1到n),每一行都有特定的收入。我想为每个用户_id选择行号属于此收入的最大收入。我想查询突出显示的行的结果


一种方法是相关子查询:

select t.*
from t
where t.revenue = (select max(t2.revenue) from t t2 where t2.user_id = t.user_id);

如果最大值有关联,则返回所有最大值行。

用您正在使用的数据库标记您的问题。谢谢,这是什么tm?我尝试了您的代码,但收到了errortm,它只是内部查询的别名,取决于您的数据库,也许您应该将其更改为“as tm”
select *,
    case when revenue = max(revenue) over (partition by user_id) then 1 else 0 end as highlight
from T
select tt.*
from #tbl tt
  join (select user_Id, max(revenue) as revenue from #tbl group by user_Id) tm on tt.user_Id = tm.user_Id and tt.revenue = tm.revenue