For simple SQL, for example
SELECT top 3 MyId FROM MyTable ORDER BY NEWID()
how to add line numbers to them so that line numbers become 1,2 and 3?
UPDATE:
I thought I could simplify my question as stated above, but that turned out to be more complicated. So, here is a more complete version - I need to give three random choices (from MyTable ) for each person, with the choice / row number 1, 2 and 3, and there is no logical connection between the person and the choices.
SELECT * FROM Person LEFT JOIN ( SELECT top 3 MyId FROM MyTable ORDER BY NEWID() ) D ON 1=1
The problem with the above SQL:
- Obviously you should add the selection / line number 1, 2, and 3.
- and what is not obvious is that the aforementioned SQL will provide each person the same selections, while I need to give different people different options
Here is the working SQL for testing:
SELECT TOP 15 database_id, create_date, 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
So please help.
NOTE: This is NOT about MySQL byt T-SQL, as their syntax is different, so the solution is different.
sql sql-server tsql
xpt
source share