2

我有一个表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

4 回答 4

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 小提琴

于 2013-10-03T10:37:13.430 回答
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
于 2013-10-03T11:21:39.157 回答
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

由于连接本身将为您提供 and 的所有组合T1,因此T2您需要所有列都没有的组合null

于 2013-10-03T10:26:55.453 回答
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
于 2019-02-03T19:14:42.810 回答