To pair people up randomly you can use
With RandonlyNumbered AS
(
SELECT
FirstName,
RN = ROW_NUMBER() OVER (ORDER BY CRYPT_GEN_RANDOM(4))-1
FROM dbo.Names
)
SELECT Name1 = MAX(CASE WHEN RN%2 = 0 THEN FirstName END),
Name2 = MAX(CASE WHEN RN%2 = 1 THEN FirstName END)
FROM RandonlyNumbered
GROUP BY RN/2
It first assigns a sequential zero based numbering to each name in random order and then assigns people in pairings according to that ordering.
If you have an odd number of names then of course one of the pairings will have a null Name2
as this does not divide evenly.
One issue with the above is that even though an ordering by RN
will also supply rows ordered by RN/2
SQL Server does not take advantage of this in the GROUP BY RN/2
- so below is a version which does leverage this better and only contains one sort operation in the execution plan...
With T1 AS
(
SELECT
FirstName,
RN = ROW_NUMBER() OVER (ORDER BY CRYPT_GEN_RANDOM(4))-1
FROM dbo.Names
), T2 AS
(
SELECT Name1 = FirstName,
Name2 = LEAD(FirstName) OVER (ORDER BY RN),
RN
FROM T1
)
SELECT Name1,
Name2
FROM T2
WHERE RN % 2 = 0