Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
vaibhavktiwari83
Aged Yak Warrior
843 Posts |
Posted - 2010-03-02 : 06:58:29
|
Interesting problem i found in another sql forum and i m not able to get it resolved.can any body solve this...GOIF EXISTS( SELECT NULL FROM sys.objects where OBJECT_ID = OBJECT_ID('A') AND Type = 'U' )BEGIN DROP TABLE AENDGOCREATE TABLE [dbo].[A]( [K] [int] NOT NULL, [varchar](50) NOT NULL)GOinsert into Aselect 1 as K,'a' as Vunion all select 1 as K,'b' as Vunion all select 2 as K,'a' as Vunion all select 2 as K,'b' as Vunion all select 4 as K,'b' as Vunion all select 5 as K,'c' as VGOIF EXISTS( SELECT NULL FROM sys.objects where OBJECT_ID = OBJECT_ID('B') AND Type = 'U' )BEGIN DROP TABLE BENDGOCREATE TABLE [dbo].[B]( [K] [int] NOT NULL, [varchar](50) NOT NULL)GOinsert into Bselect 1 as K,'a' as Vunion all select 1 as K,'b' as Vunion all select 2 as K,'a' as Vunion all select 3 as K,'b' as Vunion all select 4 as K,'a' as VGOSELECT * FROM ASELECT * FROM B-- I want output like below/*A.K A.V B.K B.V1 b 1 b2 a 2 a2 b 2 null <--warning4 b 4 null <--warning5 c null nullnull null 3 b 4 null 4 a <--warning*/Vabhav T |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2010-03-02 : 07:16:37
|
looks like you have to use FULL OUTER JOIN No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
ms65g
Constraint Violating Yak Guru
497 Posts |
Posted - 2010-03-02 : 07:36:58
|
| [code]SELECT COALESCE(A.K, (SELECT DISTINCT A.K FROM A WHERE A.K = B.K), NULL) AS [A.K],A.V AS [A.V],COALESCE(B.K, (SELECT DISTINCT B.K FROM B WHERE A.K = B.K), NULL) AS [B.K],B.V AS [B.V]FROM A FULL OUTER JOIN BON A.K = B.K AND A.V = B.V/*A.K A.V B.K B.V----------- -------------------------------------------------- ----------- --------------------------------------------------1 a 1 a1 b 1 b2 a 2 a2 b 2 NULL4 b 4 NULL5 c NULL NULLNULL NULL 3 b4 NULL 4 a*/[/code] |
 |
|
|
|
|
|
|
|