Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick a random value from a set T-SQL [duplicate]

Possible Duplicate:
Simple update statement so that all rows are assigned a different value

Is there a way to pick a random value (like a color) from a subquery? here is what I tried but getting the same value on every run:

SELECT TOP (100) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID,--Sequential number from 1 to ..
                 (SELECT TOP 1 color
                  FROM   ( VALUES (0, 'Red'),
                                  (1, 'Green'),
                                  (2, 'Yellow') ) colors(id, color)
                  ORDER  BY NEWID() )                        AS RandomColor
FROM   sys.all_columns ac1
       CROSS JOIN sys.all_columns ac2 

but if I run this piece alone, I am getting different colors:

SELECT TOP 1 color
FROM   ( VALUES (0, 'Red'),
                (1, 'Green'),
                (2, 'Yellow') ) colors(id, color)
ORDER  BY NEWID() 
like image 711
mishkin Avatar asked Oct 21 '22 22:10

mishkin


1 Answers

Something like this perhaps

select ac1.ID, r.color from
(SELECT TOP (100)
-- changed because it didn't work in mssql 2012
--ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as ID,
ROW_NUMBER() OVER (ORDER BY newid()) as ID,
ROW_NUMBER() OVER (ORDER BY newid()) as dummy
FROM sys.all_columns
order by id
) ac1
cross apply
(SELECT top 1 color FROM ( VALUES (0,'Red'),(1,'Green'),(2,'Yellow') ) colors(id,color) 
where id = dummy % 3
) r
like image 183
t-clausen.dk Avatar answered Oct 25 '22 18:10

t-clausen.dk