如果我有两列 - 一个ID字段和一个可以取10个可能值的分数字段,我如何为每个ID选择5个随机行?我知道我可以使用以下内容从表中选择5个随机行:
select *, rand() as idx
from mytable
order by idx fetch first 5 rows only
但每个ID 5行怎么样?
答案 0 :(得分:5)
您可以使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by idx order by rand()) as seqnum
from mytable t
) t
where seqnum <= 5;