How to “pick” random records with T-SQL

為{幸葍}努か 提交于 2021-01-27 03:53:47

问题


This is a simple question that is actually hard to answer, because the "picking" has a special meaning.

I need to give three random picks for each person (and give pick/row number of 1, 2, and 3). What makes it hard is that the persons and picks are from different tables and there is no logical joining between the person and picks.

The closest I can get is:

SELECT TOP 15 database_id, create_date, RowNo, cs.name FROM sys.databases
CROSS apply ( 
  SELECT top 3 Row_number()OVER(ORDER BY (SELECT NULL)) AS RowNo,*
  FROM (SELECT top 3 name from sys.all_views ORDER BY NEWID()) T
  ) cs

I know the above is not person and picks, but it a working SQL that anyone can test it out without creating person and picks tables first. And,

It illustrates the problem I'm facing --

the above SQL will give each person the same picks, whereas I need to give different person different picks.

How to do that? Thx.


回答1:


Adding a correlated condition inside the CROSS APPLY will solve your problem

SELECT TOP 15 database_id,
              create_date,
              RowNo,
              cs.NAME
FROM   sys.databases d
       CROSS apply (SELECT TOP 3 Row_number() OVER(ORDER BY (SELECT NULL)) AS RowNo, *
                    FROM   (SELECT TOP 3 NAME
                            FROM   sys.all_views v
                            WHERE  d.NAME = d.NAME --Here
                            ORDER  BY Newid()) T) cs 

Check the alias name in Where clause both LHS and RHS are from same table and same column it is just to execute the sub-query for each row in databases table




回答2:


Modifying your own answer slightly will do the job. Check this.

SELECT TOP 15 database_id, create_date, RowNo, cs.name FROM sys.databases
CROSS apply ( 
  SELECT top 3 Row_number()OVER(ORDER BY NEWID()) AS RowNo,*
  FROM (SELECT top 3 name from sys.all_views ORDER BY NEWID()) T
  ) cs 

The only change that I have done is to replace the NULL with NEWID().




回答3:


Random function is available in Sql language could use it to randomly pick a record id in a range of record ids found in the source table.

In a newer sql version I think this may work but I can't test it currently. Older sql version will not support the by rand() command. Try this let me know if it works. Later this week I can get you something that will work on sql 2000 and up. I had to do this years ago. Let me know if this works on your Sql 2008.

select top 3 from table_name order by rand()



来源:https://stackoverflow.com/questions/41030295/how-to-pick-random-records-with-t-sql

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