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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With