Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn one column into multiple

Im trying to turn a single column of data,

id
1
2
3
4
5
6

into:

col1 col2 col3
1 2 3
4 5 6

I figured it would be something to do with pivots but I’m still unsure how to accomplish this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can try using a pivot query with the help of ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY id) rn
    FROM yourTable
)

SELECT
    MAX(CASE WHEN rn % 3 = 1 THEN id END) AS col1,
    MAX(CASE WHEN rn % 3 = 2 THEN id END) AS col2,
    MAX(CASE WHEN rn % 3 = 0 THEN id END) AS col3
FROM cte
GROUP BY (rn - 1) / 3;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading