sql - 如何在类别中找到最大值

时间:2017-02-06 21:39:05

标签: sql greatest-n-per-group

如何在sql中获得这样的输出。我尝试过分组,但它没有给出几个月,是否有更简单的方法来做到这一点。

select * from t1 order by 1,2 ;
 id | month | amnt
----+-------+------
  1 | feb   |   50
  1 | jan   |   20
  2 | apr   |   30
  2 | feb   |   50
  2 | jan   |   30
  2 | mar   |   70
(6 rows)

Output
=========

 id | month | amnt
----+-------+------
  1 | feb   |   50
  2 | mar   |   70

1 个答案:

答案 0 :(得分:1)

如果你有窗口功能

Select Top 1 with ties *
 From  YourTable
 Order By Row_Number() over (Partition By id order by amnt desc)

返回

id  month   amnt
2   mar     70
1   feb     50