我有两个选择查询,它们返回结果集以下。
ResultSet1:
FIELD_NAME DISPLAY MASK DEFAULTVALUE
LOANTYPE 1 Test LoanType 2
PREAPPROVAL 1 Test Preapproval 2
ResultSet2:
FIELDNAME DISPLAY MASK DEFAULTVALUE
LOANTYPE NA NA
INTEREST NA NA
HOMETYPE NA NA
PREAPPROVAL NA NA
PURCHASERTYPE NA NA
PURPOSE NA NA
PREAPPROVAL NA NA
我想得到如下结果。任何帮助将不胜感激。
FIELD_NAME DISPLAY MASK DEFAULTVALUE
LOANTYPE 1 Test LoanType 2
PREAPPROVAL 1 Test Preapproval 2
INTEREST NA NA
HOMETYPE NA NA
PREAPPROVAL NA NA
PURCHASERTYPE NA NA
PURPOSE NA NA
PREAPPROVAL NA NA
这里需要删除重复的LOANTYPE和PREAPPROVAL值。我尝试了两个CTE,并进行了正确的联接。但这没有给出预期的结果。
答案 0 :(得分:1)
您可以尝试使用窗口函数row_number()
with cte as
(
SELECT *,row_number() over(partition by FIELD_NAME order by DISPLAY desc,MASK desc,DEFAULTVALUE desc) rn
FROM (
Query1
UNION
Query2
) t
) select * from cte where rn=1
答案 1 :(得分:1)
您应该可以使用外部联接和coalesce()
:
select r2.field_name,
coalesce(r1.display, r2.display) as display,
coalesce(r1.mask, r2.mask) as mask,
coalesce(r1.defaultvalue, r2.defaultvalue) as defaultvalue
from resultset2 r2 left join
resultset1 r1
on r1.field_name = r2.field_name;
答案 2 :(得分:0)
您可以在下面使用左联接和CASE WHEN尝试
如果table2值为空,则可以使用Coalesce()函数代替CASE
select
a.FIELD_NAME,
case when a.DISPLAY='NA' then b.display else a.display end as DISPLAY,
case when a.MASK='NA' then b.Mask else a.mask end as MASK,
case when a.DEFAULTVALUE='NA' then b.defaultvalue else a.defaultvalue end as Defaultvalue
from resultset2 a left join resultset1 b
on a.loantype=b.loadtype