Kric
Kric

Reputation: 103

SQL Same ID Populated in Multiple Rows with Different Column Values Populated--Need One ID in One Row

I have a table like following:

ID     Col1    Col2    Col3    Col4
001     A       
001             B   
001                     C     
001                              D
002             X
002                              Y

I want the result like the following:

ID    Col1    Col2    Col3    Col4
001    A       B       C       D
002            X               Y

The challenge is the number of columns is unknown, maybe this it has a Col5 or even Col10. Any thoughts? Much appreciated.

Upvotes: 1

Views: 647

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269603

You can do this with aggregation:

select id, max(col1) as col1, max(col2) as col2, max(col3) as col3, max(col4) as col4
from t
group by id;

This assumes that there are no duplicates within a column for an id.

For additional columns, you would need to add additional clauses to the select statement.

Upvotes: 1

Related Questions