需要帮助自我加入

时间:2013-10-03 09:58:20

标签: sql sql-server self-join

我有一个表 XYZ

ID   A       B       C
1    abc     ygh     NULL
2    fgfd    bjh     NULL
3    jhkj    fgd     cgbvc
1    NULL    NULL    yr
2    NULL    NULL    jg

我需要在上表中进行自联接才能获得匹配的ID。我正在尝试使用以下查询:

Select T1.ID, T1.A, T1.B, T2.C
From XYZ T1
INNER JOIN XYZ T2
where T1.ID = T2.ID

但是没有低于结果:

1   abc     ygh     yr
2   fgfd    bjh     jg

请指教。克里希纳

4 个答案:

答案 0 :(得分:2)

为什么要使用self join

<强> Tip: 'A' + NULL=NULL

select ID,max(A) A,max(B) B,max(C) C
from XYZ
where A+B+C is null
group by ID

<强> SQL FIDDLE

答案 1 :(得分:0)

我想你想要这样的东西:

select T1.ID, T1.A, T1.B, T2.C from XYZ T1
inner join XYZ T2
on T1.ID = T2.ID
where T1.A is not null and T1.B is not null and T2.C is not null

由于加入自身会为您提供T1T2的所有组合,您希望所有列都不是null

答案 2 :(得分:0)

您可以使用以下查询,但它基于WHERE子句。

select ID,A,B,C from (
select *, ROW_NUMBER() over (partition by id order by s desc ) as 'x' from (
Select  T1.ID,T1.A,T1.B,T2.C,ROW_NUMBER() over (partition by t1.id order by     
t1.a,t1.b ,t1.c ) as s
From xyz T1 JOIN xyz T2 on T1.ID = T2.ID ) abc ) xyz
where x = 1

答案 3 :(得分:0)

鉴于此表结构,您还可以使用COALESCE

SELECT 
    COALESCE(a.A, b.A) A,
    COALESCE(a.B, b.B) B,
    COALESCE(a.C, b.C) C
FROM 
    XYZ a 
JOIN 
    XYZ b ON a.Id = b.Id
WHERE
    a.A IS NULL OR a.B IS NULL OR a.C IS NULL