Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL single column split over multiple columns

I want to split the single column result from a query into 4 columns:

Sample source: (Select [FirstName from User)
Peter
Mary
John
Tina
Carl
Jane
Bill
Sarah

I want to look like this:

Column1   Column2   Column3   Column4  
Peter     Mary      John      Tina  
Carl      Jane      Bill      Sarah
like image 243
callisto Avatar asked Jul 09 '12 08:07

callisto


2 Answers

You need to have a unique column to ORDER BY to get deterministic results but something along these lines should work.

;WITH T
     AS (SELECT [FirstName],
                ( ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 ) / 4 AS Row,
                ( ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 ) % 4 AS Col
         FROM   [User])
SELECT [0] AS Column1,
       [1] AS Column2,
       [2] AS Column3,
       [3] AS Column4
FROM   T PIVOT (MAX(name) FOR Col IN ([0], [1], [2], [3])) P 
ORDER BY Row
like image 61
Martin Smith Avatar answered Sep 28 '22 14:09

Martin Smith


Here you have tons of options, look for the one is more suited for your case: Create columns from list of values

Previous link directs to even more information

like image 36
Yaroslav Avatar answered Sep 28 '22 14:09

Yaroslav