HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

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

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
rowscolumnsqlintosplitmultiplespecificserverrowaccording

Problem

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

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

Help!

Solution

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;

Code Snippets

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;

Context

StackExchange Database Administrators Q#170898, answer score: 6

Revisions (0)

No revisions yet.