You can do this by using the LEAD()
function in conjunction with ROW_NUMBER()
in SQL Server 2012, or in SQL 2008 Server you can use the ROW_NUMBER()
function and a self-join.
SQL Server 2012:
;WITH cte AS (SELECT FN + ' ' + LN AS Team1
, LEAD(FN + ' ' + LN,1) OVER(ORDER BY (SELECT 1)) AS Team2
,ROW_NUMBER() OVER(ORDER BY (SELECT 1))RN
FROM Table1)
SELECT Team1, Team2
FROM cte
WHERE RN%2 > 0
Demo: SQL Fiddle
SQL Server 2008:
;WITH cte AS (SELECT FN + ' ' + LN AS Team
,ROW_NUMBER() OVER(ORDER BY (SELECT 1))RN
FROM Table1)
SELECT a.Team AS Team1
,b.Team AS Team2
FROM cte a
JOIN cte b
ON a.RN = b.RN-1
WHERE a.RN%2 > 0
Demo: SQL Fiddle
The ROW_NUMBER()
function adds a number to each row, it requires an ORDER BY
clause, so if you want the ordering to not be arbitrary you will replace (SELECT 1)
with a field from your table.
Edit: I see that you want to randomize this, you can use ORDER BY NEWID()
to get a random ordering, but when doing so you cannot count on the cte
as it could result in team 1 being the same as team 2, instead you'll want to use a temp table:
SELECT FN + ' ' + LN AS Team
,ROW_NUMBER() OVER(ORDER BY NEWID()) AS RN
INTO #t
FROM Table1
;
SELECT a.Team AS Team1
,b.Team AS Team2
FROM #t a
JOIN #t b
ON a.RN = b.RN-1
WHERE a.RN%2 > 0
Demo: SQL Fiddle