从每个组中选择顶行

时间:2016-05-26 19:56:55

标签: mysql select group-by row

我必须根据两列的最大值检索每组的顶行。

这是表格:

tag_series_id   |   tag_season_num  |   tag_episode_num
269653              2                   24
269653              3                   1
269653              3                   2
269653              3                   3   
281593              1                   9
281593              1                   11
281593              1                   10

结果集应该是最大tag_season_numtag_episode_num的记录。 tag_season_num应该是更高的优先级。

结果集应为:

tag_series_id   |   tag_season_num  |   tag_episode_num
269653              3                   3   
281593              1                   11

这些是我尝试失败的一些尝试:

SELECT tag_series_id, tag_season_num, tag_episode_num, tag_watch_status
FROM taggedshows WHERE 
GROUP BY tag_series_id, tag_season_num
ORDER BY tag_season_num desc, tag_episode_num desc;

SELECT tag_series_id, tag_season_num, tag_episode_num 
FROM (SELECT * from taggedshows
ORDER BY tag_series_id, tag_season_num desc, tag_episode_num desc) x
GROUP BY tag_series_id;

SELECT tag_series_id, MAX(tag_season_num), MAX(tag_episode_num)
FROM taggedshows
GROUP BY tag_series_id;

1 个答案:

答案 0 :(得分:1)

有点嵌套,但我认为你需要两级子查询

select * from taggedshows
where (tag_season_num, tag_episode_num)  in 
    (select tag_season_num, max(tag_episode_num)  from  taggedshows
    where ( tag_series_id , tag_season_num) in 
    (select tag_series_id max(tag_season_num)  from taggedshows
    group by tag_seried_id)
    group by tag_season_num)