1

我省略了最后一步之前的步骤。我得到这样的表:year, month, postid, clicks。我如何获得postid每个year, 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 回答