My table looks like this:
GroupID INT NOT NULL
SomeValue INT NOT NULL
I'd like to keep rows with the same GroupID
together in the result set. The groups themselves should be ordered randomly, though. SomeValue
is supposed to be the secondary sort criterion. Like this:
GroupID, SomeValue
13, 1
13, 2
7, 1
7, 2
11, 1
11, 2
...
ORDER BY GroupID, SomeValue
does not order groups randomly. ORDERBY NEWID()
is totally random. ORDER BY SomeHash(GroupID), SomeValue
comes to mind but I need a new random order each time.
How can this be done?
Best Answer
You only need a random order for the
GroupID
values, so first get these distinct values and a random number for each, in a derived table:If you already have a
Groups
table which holds theGroupID
values, you can replace thatFROM tablename GROUP BY GroupID
withFROM Groups
.