我必须加入2次观看view_a和view_b view_a具有列id,地址1,地址2,城市,州,cntry view_b id,frst_name,last_name,type,date,job_title
期望的结果
ID,名称,地址1,地址,城市,州,CNTRY,JOB_TITLE
我的查询条件是:
1.加入id列的两个视图
2.按日期排序desc
3.连接first_name和last_name
4.类型等于“官员”
5.如果有一名以上的官员,那么只产生一名官员,即根据日期排在第一位
6.如果没有人员,则结果中的name和job_title列的值为null。
查询我使用过:
select
*
from
view_a A
join
(
select
(first_name || ' ' || last_name) as name,
job_title,
id
from
view_b
where
type = 'officer'
and
id is not null
order by date desc fetch first 1 row only
) B
on A.id=B.id
但是这个查询只产生一个结果。我正在使用Oracle 12c。这些视图中有大约800K记录。
答案 0 :(得分:1)
你可以这样做:
select id,
name,
address1,
address2,
city,
state,
cntry,
job_title
(select
a.id,
nvl2(nvl(b.first_name, b.last_name),b.first_name||' '||b.last_name,null) Name,
a.address1,
a.address2,
a.city,
a.state,
a.cntry,
b.job_title,
a.date
row_number() over (partition by a.id order by a.date desc nulls last) rn
from
view_a a left outer join
view_b b
on a.id = b.id
and b.type = 'officer')
where rn = 1
order by date desc nulls last;
答案 1 :(得分:0)
以下也解决了这个问题:
SELECT *
FROM view_a a
LEFT JOIN (SELECT name, job_title, id
FROM (SELECT (first_name || ' ' || last_name) AS name,
job_title,
id,
ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC) rn
FROM view_b
WHERE TYPE = 'officer' AND id IS NOT NULL)
WHERE rn = 1) b
ON a.id = b.id