Sql-server – split a row into multiple rows in sql server according to a specific column

sql server

I have table a having fields id,val and identical table b having fields id,val.

when i am writing an inner join for different data in rows

SELECT * FROM a left join b on a.id = b.id WHERE ( a.id != b.id or
a.val != b.val)

i am getting like below
enter image description here

i want to split this table row into two rows. Help me to write a query to split this data and getting an output table like below
enter image description here

Help!

Best Answer

You can generate the extra row(s) by doing an unpivot using a cross apply and the table value constructor.

select c.id,
       c.val
from dbo.a 
  inner join dbo.b
    on a.id = b.id
  cross apply (values(a.id, a.val),
                     (b.id, b.val)) as c(id, val)
where a.val <> b.val;