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

Split multiple rows into multiple columns

I have a table with 2 Columns:

SELECT
ID ,Project
FROM projects

The table shows me the projects in which the Employee(ID) is working in:

ID | Project
--------------
ID1| Project1
ID1| Project2
ID1| Project3
ID1| Project4
ID2| Project1
ID2| Project2
ID3| Project1
ID3| Project2
ID3| Project3

In case when one employee is working in more than 1 project, i need to split the different projects into different columns named . The result should be looking like 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

ID |   Col1   |   Col2   |   Col3   |   Col4   |   Col5  |
----------------------------------------------------------
ID1| Project1 | Project2 | Project3 | Project4 |   NULL  |
ID2| Project1 | Project2 |   NULL   |   NULL   |   NULL  |
ID3| Project1 | Project2 | Project3 |   NULL   |   NULL  |

Since there are never more than 5 projects, the number of the columns can be fixed at 5.

I tried with different row_number() and pivot approaches but failed due to my inexperience.

>Solution :

We can use a pivot query with the help of ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Project) rn
    FROM projects
)

SELECT
    ID,
    MAX(CASE WHEN rn = 1 THEN Project END) AS Col1,
    MAX(CASE WHEN rn = 2 THEN Project END) AS Col2,
    MAX(CASE WHEN rn = 3 THEN Project END) AS Col3,
    MAX(CASE WHEN rn = 4 THEN Project END) AS Col4,
    MAX(CASE WHEN rn = 5 THEN Project END) AS Col5
FROM cte
GROUP BY ID
ORDER BY ID;

If there be some other column which should determine the ordering of projects for each ID, then update the call to ROW_NUMBER.

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