db2 select x random rows for a given id

2019-09-11 09:52发布

If I have two columns - an ID field and a score field that can take 10 possible values, how can I select 5 random rows per ID? I know I can select 5 random rows from a table by using the following:

select *, rand() as idx
from mytable 
order by idx fetch first 5 rows only

but how about 5 rows per ID?

标签: sql random db2
1条回答
来,给爷笑一个
2楼-- · 2019-09-11 10:35

You can do this using 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;
查看更多
登录 后发表回答