3

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!

asked Apr 13, 2017 at 7:29
1
  • left join on a.id = b.id wont return any (a.id <> b.id) Commented Apr 13, 2017 at 7:38

2 Answers 2

6

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;
answered Apr 13, 2017 at 8:02
1
  • Comments moved to chat as requested. Commented Apr 13, 2017 at 13:35
1

As far as your query uses a LEFT JOIN b ON a.id = b.id you can change your WHERE clause to WHERE (a.val != b.val) because you wont receive any record where a.id <> b.id

That said, to divide the results you can use a UNION by selecting all records from table a, plus all records from table b that match your WHERE clause.

create table a (id int, val varchar(10));
create table b (id int, val varchar(10));
insert into a values (1,'aaa'),(2,'bbb'),(3,'ccc'),(4,'ddd');
insert into b values (1,'ddd'),(5,'bbb'),(3,'xxx'),(7,'ddd');
GO
8 rows affected
SELECT * FROM a left join b on a.id = b.id WHERE ( a.id != b.id or a.val != b.val)
GO
id | val | id | val
-: | :-- | -: | :--
 1 | aaa | 1 | ddd
 3 | ccc | 3 | xxx
SELECT a.* FROM a left join b on a.id = b.id WHERE (a.val <> b.val)
UNION
SELECT b.* FROM a left join b on a.id = b.id WHERE (a.val <> b.val)
GO
id | val
-: | :--
 1 | aaa
 1 | ddd
 3 | ccc
 3 | xxx

dbfiddle here

answered Apr 13, 2017 at 7:39
2
  • Perfect!!!!!!!!!!!!!!!!!!!!! it Works for me Commented Apr 13, 2017 at 8:26
  • If it works pls accept this as an Ans Commented Jun 16, 2021 at 7:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.