Thursday, August 10, 2017

Merge two rows into one row SQL

I have a requirement in which i need to show two column in one row .The simplest way to merge rows is with an aggregate function such as MIN/MAX. These functions will ignore nulls.

Before
EmployeeNo  Column1   Column2
================================
1           |  NULL       | Column2
1           |  Column1    |   NULL 

Sql
SELECT
  EmployeeNo,
  MAX(Column1) AS Column1,
  MAX(Column2) AS Column2
FROM MyTable
GROUP BY EmployeeNo

After Result
EmployeeNo  Column1   Column2
================================
1          | Column1  |   Column2
PS :
If you have a sub query to get a columns from other table it will not work in this you need to make a Derived Tables or you can use left join 
Reference:
https://dba.stackexchange.com/questions/67831/want-to-combine-two-rows-into-one-row

No comments:

Post a Comment