我省略了最后一步之前的步骤。我得到的表格如下:year, month, postid, clicks
。如何为每个postid
群体获得前缀year, month
?
例如,我有数据:
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
答案 0 :(得分: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
小提琴here