SQL Concat every other Row to return a string ["FistName LastName", "FisrtName LastName"] ,

StackOverflow https://stackoverflow.com/questions/20596661

  •  02-09-2022
  •  | 
  •  

Question

This is beyond my knowledge any help would great!

I have a SQL Server table named RegisteredUsers that contains FirstName and LastName. I need to build a string ["FirstName LastName", "FirstName LastName"] for every 2 rows. I can build the string but I need to get

The first row to contain the results of 1st and 2nd rows FirstName LastName FirstName LastName The second row to contain 3rd and 4th FirstName LastName FirstName LastName and so on.

I am attempting to randomize and pair users up

I hoping to get something link this

Team1 | Team2
1 FN LN  | FN LN
2 FN LN  | FN LN
3 FN LN  | FN LN
4 FN LN  | FN LN

Thank for the help

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top