Given the table as an example:
I want to sort, between the lines with the same order number, a single line, that is, one of order 1, one of order 2 and one of order 3, randomly. I need a generic solution, which applies to a table with n orders.
You can do with ROW_NUMBER () too ...
SELECT ORDEM, RODADA
FROM
(
SELECT ORDEM, RODADA, ROW_NUMBER() OVER(PARTITION BY ORDEM ORDER BY NEWID()) AS ROWORDER
FROM #TMP_RODADAS
) TEMP
WHERE
ROWORDER = 1
Try this:
SELECT t.ordem,
(SELECT TOP 1 rodada FROM tabela WHERE ordem = t.ordem ORDER BY NEWID())
FROM (SELECT DISTINCT ordem FROM tabela) t
The call to NEWID()
within ORDER BY
generates a GUID for each row returned. It is not exactly random, but it is generic and simple enough, since SQL Server has no specific function to generate a random number.
One solution is to use subquery
with ROW_NUMBER
using PARTITION BY
for the column you want to be grouping and sorting by NEW_ID
that will guarantee randomization:
SELECT x.*
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY t.ordem ORDER BY NEWID()) AS sequencia,
t.*
FROM tabela t) x
WHERE sequencia <= 1
In% with% above:
query
to get the returns of clusters that will be used outside ROW_NUMBER
; subquery
by the column that will be used to group; PARTITION BY
that will ensure that the sequence will be random; NEW_ID
case) to limit the number of records we want by grouping (in the example it would only be 1 per group); Returns the sequential number of a row in a partition of a result set, starting at 1 for the first row of each partition.
Creates a unique value of type
NEWID
.
Free translation:
Create a unique value of type
uniqueidentifier
;
taking advantage of colleague Vitor's idea for order by newid (), because it seems to me that rand () did not work.
select distinct
t.ordem,
(select top 1
x.rodada
from temp x
where x.ordem = t.ordem
order by newid()) as rodada
from temp t
look at SQLFiddle: link