Skip to content
Advertisement

Move values in different columns to one row

I have the following table:

CREATE TABLE dbo.Examples 
(
    Id int not null,
    row1 nvarchar(50) null,
    row2 nvarchar(50) null,
    row3 int null 
)

With this sample data:

INSERT INTO Examples (id, row1, row2, row3)
VALUES (1, 'Value1', NULL, NULL),
       (1, NULL, 'Value1', NULL),
       (1, NULL, NULL, 28)

Id is my primary key, and this should be UNIQUE in the table. This is possible for all of my rows, if I simply move all values up to one row in the above example.

I only need to make this work when data looks like it is in the above example. This means that the desired outcome would look like this:

VALUES (1, 'Value1', 'Value1', 28) 

one row, where all the values are moved to one row.

How do I accomplish this?

Advertisement

Answer

You can use simple aggregation, does this work for you?

select id, Max(row1) row1, Max(row2) row2, Max(row3) row3
from examples
group by id
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement