1

最後のステップの前のステップを省略します。次のようなテーブルが表示されますyear, month, postid, clickspostidyear, monthグループのトップKを取得するにはどうすればよいですか?

たとえば、次のデータがあります。

2012,1,a,5
2012,1,b,3
2012,1,c,8
2012,2,a,2
2012,2,c,5
2012,2,d,6

と仮定するとk=2、次のような結果が必要です。

2012,1,c,8
2012,1,a,5
2012,2,d,6
2012,2,c,5
4

1 に答える 1

2

これを試してみてください:

select postid, clicks,
    @num := if(@year = @year and @month = month, @num + 1, 1) row_number,
    @year := year year, @month := month month
from (
    select * from t
    order by year, month, clicks desc
) s, (select @num := 0, @year := '', @month := '') init
group by year, month, postid, clicks
having row_number <= 2
order by year, month, clicks desc

ここでフィドル

于 2012-04-16T18:45:25.443 に答える