简体   繁体   English

Oracle使用5个条件加入2个视图

[英]Oracle Join 2 views with 5 conditions

i have to join 2 views view_a and view_b. 我必须加入2个视图view_a和view_b。
view_a has columns id,address1,address2,city,state,cntry view_b id,frst_name,last_name,type,date,job_title view_a具有列id,address1,address2,city,state,cntry view_b id,frst_name,last_name,type,date,job_title

desired result 理想的结果
id,Name,address1,address2,city,state,cntry,job_title id,名称,地址1,地址2,城市,州,国家,职务

Conditions for my query are: 我查询的条件是:
1. join both views on id column. 1.在id列上加入两个视图。
2. order by date desc 2.按日期排序
3. concatenate first_name and last_name 3.串联first_name和last_name
4. type equals to "officer" 4.类型等于“军官”
5. If there are more than one officer then yield only one officer ie, one top row based on the date. 5.如果有多名官员,则仅产生一名官员,即基于日期的第一行。
6. If there is no officer then have null value for the name and job_title column in the result. 6.如果没有人员,则结果中的name和job_title列的值为空。

Query I have used: 我使用过的查询:

   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  

But this query is yielding only one result. 但是此查询仅产生一个结果。 I'm using Oracle 12c. 我正在使用Oracle 12c。 there are about 800K records in these views. 这些视图中大约有80万条记录。

You can do this: 你可以这样做:

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;

The following also solved the problem: 以下还解决了该问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM