db2 select x random rows for a given id

拜拜、爱过 提交于 2019-12-12 03:54:05

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/40769451/db2-select-x-random-rows-for-a-given-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!