将2条记录解析为一个并联接表

时间:2018-12-04 19:55:09

标签: sql oracle join

已审核

    +----+--------------------- +------+-------+
    | id |   POS  |  Review Date| Role |app ID |
    +----+----------------------+------+-------+
    |  1 |   A    | 2018-12-03  |  E   |  170  |
    |  2 |   A    | 2018-12-04  |  P   |  170  |
    |  3 |   B    | 2018-12-01  |  E   |  180  |
    |  4 |   B    | 2018-12-05  |  P   |  180  |
    |  5 |   B    | 2018-12-05  |  X   |  190  |
    |  6 |   B    | 2018-12-05  |  w   |  195  |
    |  7 |   C    | 2018-12-06  |  w   |  170  |
    +----+--------+-------------+------+-------+

呼叫中心

    +----+------+-----+------+
    | id |  POS |  Emp|  yrs |
    +----+------+-----+------+
    |  1 |   A  |  F  |   4  |
    |  2 |   B  |  F  |   3  |
    |  3 |   C  |  P  |   3  |
    +----+------+-----+------+

需要呼叫中心加入;另外,也忘记了可能有很多角色(x,w,u,t),但是只是想将角色E和P的审阅日期结合起来。

需要为每个唯一的POS返回一个记录,包括仅角色E和P的两个审阅日期;仅应用程序ID 170;来自call_center的EMP和yrs,加入POS

例如:

POS Review_Date(role E) Review_Date(role P) EMP Yrs app ID
A   2018-12-03          2018-12-04           F   4   170

查看更新的表格

请使用Oracle语法

3 个答案:

答案 0 :(得分:3)

您可以使用case when来过滤与所需角色匹配的日期,并将其与group by(和max)结合使用:

select Pos,
       max(case Role when 'E' then review_date end) review_E,
       max(case Role when 'P' then review_date end) review_P
from reviewed
group by Pos

您也可以使用Oracle 11g以来可用的pivot子句:

select *
from (
    select Pos, Role, review_date
    from reviewed
)
pivot 
(
    max(review_date)
    for Role
    in ('E', 'P')
);

答案 1 :(得分:0)

我将使用两个CTE:

with
e as (
  select * from reviewed where role = 'E'
),
p as (
  select * from reviewed where role = 'P'
)
select
  coalesce(e.pos, p.pos) as pos,
  e.review_date as review_date_role_e,
  p.review_date as review_date_role_p
from e
full outer join p on e.pos = p.pos
order by coalesce(e.pos, p.pos)

答案 2 :(得分:0)

select A.POS, A.review_date as review_date1, a.ROLE as ROLE1, B.review_date as 
review_date2, B.ROLE as ROLE2
from reviewed a
left join reviewed b
on a.POS = b.POS
and a.review_date < b.review_date
where B.ROLE is not null
;