Search code examples
sqlt-sqlsql-server-2012sql-merge

Combine two rows based on common ID


I have a query that returns two lines per ID. I would like to be able to merge these into one single row, based on the ID.

There will only ever be two rows per ID. As in the example below, one row will only ever contain ColumnA and the other row will contain ColumnB.

So this is a simplified version of how the data looks at the moment:

enter image description here

And this is how I would like it to be, although I'm not entirely sure how to go about it:

enter image description here


Solution

  • You can do this by aggregation:

    select ID, max(ColumnA) ColumnA, max(ColumnB) ColumnB 
    from TableName
    group by ID