分析我的稀碎答案:

  • 妄图用Limit限制最终数据条数

(1)

select tag as tid,uid,
row_number() over (partition by tag order by tag,max(score) desc,
                  min(score) desc,er.uid desc) as ranking
from exam_record as er
join examination_info as ei
on er.exam_id=ei.exam_id
group by tid,uid
order by tid,ranking limit 3

alt 这样仅输出总体前三行

(2)

select tag as tid,uid,
row_number() over (partition by tag order by tag,max(score) desc,
                  min(score) desc,er.uid desc) as ranking
from exam_record as er
join examination_info as ei
on er.exam_id=ei.exam_id
group by tid,uid
order by tid,ranking limit 6

alt

  • 妄图用having限制最终数据条数
select tag as tid,uid,
row_number() over (partition by tag order by tag,max(score) desc,
                  min(score) desc,er.uid desc) as ranking
from exam_record as er
join examination_info as ei
on er.exam_id=ei.exam_id
group by tid,uid
having ranking<=3

会报错:You cannot use the alias 'ranking' of an expression containing a window function in this context.

即由窗口函数得到的变量不可用在having语句中。

提交答案:

select tid,uid,ranking from
(
    select tag as tid,uid,
row_number() over (partition by tag order by tag,max(score) desc,
                  min(score) desc,er.uid desc) as ranking
from exam_record as er
join examination_info as ei
on er.exam_id=ei.exam_id
group by tid,uid
) as q
where ranking<=3