我有两个表,即表1 和表2
表1
custId--custName--custAge
c1--c1name--32
c2--c2name--41
c3--c3name--41
表2
custId--verified--custName
c1--Y--c1FullName
c2--N--c2FullName
我需要加入Table1和Table2,因此如果表2中的验证列为Y,我需要Table2中的custName而不是Table1。
因此,所需的输出为:(覆盖表2中的custName列,如果验证列为该custId的Y )
custId--custName--custAge
c1--c1FullName--32
c2--c2name--41
c3--c3name--41
我写了以下查询,但没有给出正确的结果。请帮忙。
select T1.custId, NVL(T2.custName, T1.custName),T1.custAge
from Table1 T1
left join Table2 T2 on T1.custId=T2.custId and T2.verified='Y'
答案 0 :(得分:4)
您可以使用CASE
语句来实现此目的:
SELECT tab1.custId,
CASE
WHEN (tab2.verified = 'Y')
THEN tab2.custName
ELSE tab1.custName
END AS CustName,
tab1.custAge
FROM Table1 tab1
LEFT JOIN Table2 tab2 ON tab1.custId = tab2.custId
在此处查看 - > http://rextester.com/EVOMK25746(这个小提琴基于 SQL Server
构建,但是,该查询也可以在 Oracle
数据库上运行< / em>的)
希望这有帮助!!!
答案 1 :(得分:1)
尝试此查询一次..
select * into #tab1 from
(
select 'c1' custId,'c1name' custName,31 custAge
union all
select 'c2' ,'c2name' ,41
union all
select 'c3' ,'c3name' ,41
) as a
select * into #tab2 from
(
select 'c1' custId,'Y'verified,'c1FullName' custName
UNION ALL
SELECT 'c2','N','c2FullName '
) as a
SELECT T1.custId,CASE WHEN T2.verified='Y' THEN T2.custName ELSE T1.custName END AS CUSTNAME,T1.custAge FROM #tab1 T1
LEFT JOIN #tab2 T2 ON T1.custId=T2.custId
答案 2 :(得分:0)
select custId, custName, custAge
from Table1
natural join
( select custId
from Table2
where verified='N' ) t2
union
select custId, custName, custAge
from ( select custId, custAge from Table1 ) t1
natural join
( select custId, custName
from Table2
where verified='Y' ) t2;