select two maximum values per person based on a column partition

醉酒当歌 提交于 2019-12-11 04:39:50

问题


Hi if I have the following table:

Person------Score-------Score_type
1           30          A
1           35          A
1           15          B
1           16          B
2           74          A
2           68          A
2           40          B
2           39          B

Where for each person and score type I want to pick out the maximum score to obtain a table like:

Person------Score-------Score_type
    1           35          A
    1           16          B
    2           74          A
    2           40          B

I can do this using multiple select statements, but this will be cumbersome, especially later on. so I was wondering if there is a function which can help me do this. I have used the parititon function before but only to label sequences in a table....


回答1:


select person,
       score_type,
       max(score) as score
from scores
group by person, score_type
order by person, score_type;

With "partition function" I guess you mean window functions. They can indeed be used for this as well:

select person
       score_type, 
       score
from (
  select person, 
         score_type, 
         score,
         row_number() over (partition by person, score_type order by score desc) as rn
  from scores
) t 
where rn = 1
order by person, score_type;



回答2:


Using the max() aggregate function along with the grouping by person and score_type should do the trick.



来源:https://stackoverflow.com/questions/18593754/select-two-maximum-values-per-person-based-on-a-column-partition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!