开发者

How to make this sql statement

I have 2 tables:

T1(IDa,IDb) : has data like this

    IDa IDb  
    1   2  
    3   4  
    5   6  
    7   8

and T2(IDc,IDd) :开发者_StackOverflow中文版 with data like this

    IDc IDd  
    1   2  
    4   5  
    3   6  
    7   8  

and the Identity for each table is the pair of IDs:

  • T1, Identity is IDa and IDb
  • T2 is IDc and IDd

The question is: How to retrieve the "Not matched" records from the two tables??? In this case,

  • the matched are 1,2 and 7,8
  • the "not matched" are: 3,4 $ 5,6 $ 4,5 $ 3,6

I can do that using strings and concatenation. Did anyone have a method using inner join or any other method??


DECLARE @Result nvarchar(max)


SELECT @Result = ISNULL(@Result + '$','') + 
       CAST(ISNULL(IDa,IDc) AS VARCHAR(5)) + ',' +  
            CAST(ISNULL(IDb,IDd) AS VARCHAR(5))
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND  T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL

Edit Of course if the $ and , is not required just use

SELECT  ISNULL(IDa,IDc), ISNULL(IDb,IDd)
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND  T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL

Or another way, just for kicks (MS SQL Server 2005+)

SELECT IDa, IDb from T1
EXCEPT
SELECT IDc, IDd from T2
UNION ALL
(
SELECT IDc, IDd from T2
EXCEPT
SELECT IDa, IDb from T1
)


select IDa, IDb from T1
where not exists (select 1 from T2 where T2.IDc = T1.IDa and T2.IDd = T1.IDb)
union all
select IDc, IDd from T2
where not exists (select 1 from T1 where T2.IDc = T1.IDa and T2.IDd = T1.IDb)

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜