sql-servert-sqlinsertgroup

T-SQL to merge data from different rows under different columns


I have a table with data for each column distributed in different rows. Need help with getting all the data into a single row.

Column A Column B Column C Column D Column E
Jacob Joseph Ben NULL NULL
Jacob Joseph NULL NULL Reuben
Jacob Joseph NULL Judah NULL

I want to populate all the data in one row like below:

Column A Column B Column C Column D Column E
Jacob Joseph Ben Judah Reuben

I am new to T-SQL and unable to get to where I want. Please help.

I initially had an Excel sheet with the data scattered across the columns in an odd way. After a lot of reformatting I got it to this point and imported into SQL Server to fix it through T-SQL. I tried a few things with insert into table selecting from the table but unable to arrange the data in a single row.


Solution

  • You can use aggregate and GROUP BY to solve this

    SELECT 
        ColumnA,
        ColumnB,
        MAX(ColumnC) AS ColumnC,
        MAX(ColumnD) AS ColumnD,
        MAX(ColumnE) AS ColumnE
    FROM 
        YourTable
    GROUP BY 
        ColumnA, ColumnB;
    

    Here is the sample dbfiddle