我有一个表 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
请指教。克里希纳
答案 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
由于加入自身会为您提供T1
和T2
的所有组合,您希望所有列都不是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