如何在使用union时模拟on条件?

ezykj2lf  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(215)

我有这样一个问题:

select
    yyyy_mm_dd,
    xml_id,
    feature,
    status
from
    schema.t1
where
    yyyy_mm_dd >= '2019-02-02'

union all

select
    yyyy_mm_dd,
    p_id as xml_id,
    'payment' as feature,
    case
        when payment = 1 then 1
        else 0
    end as status
from
    schema.t2
where
    yyyy_mm_dd >= '2019-02-02'

有没有办法让我保证 union 有比另一个更重要的约会吗?有了连接,我就可以用 on 条件 yyyy_mm_dd . 我想维持工会,但只到最大日期,这是在两个表中可用。
有没有比我提出的解决方案更有效的方法?

select
    c.yyyy_mm_dd,
    xml_id,
    feature,
    status
from
    schema.t1 c
left join(
    select
        max(yyyy_mm_dd) as yyyy_mm_dd
    from
        schema.t2
    where
        yyyy_mm_dd >= '2020-10-01'
) m on m.yyyy_mm_dd = c.yyyy_mm_dd
where
    c.yyyy_mm_dd >= '2020-10-01'
    and m.yyyy_mm_dd is null

union all

select
    c.yyyy_mm_dd,
    p_id as xml_id,
    'payment' as feature,
    case
        when payment = 1 then 1
        else 0
    end as status
from
    schema.t2 c
left join(
    select
        max(yyyy_mm_dd) as yyyy_mm_dd
    from
        schema.t1
    where
        yyyy_mm_dd >= '2020-10-01'
) m on m.yyyy_mm_dd = c.yyyy_mm_dd

where
    c.yyyy_mm_dd >= '2020-10-01'
    and m.yyyy_mm_dd is not null
eivnm1vs

eivnm1vs1#

创建2 CTE ,然后仅选择每个cte中具有匹配的行 yyyy_mm_dd 在另一个cte中:

with 
  cte1 as (
    select yyyy_mm_dd, xml_id, feature, status
    from schema.t1
    where yyyy_mm_dd >= '2019-02-02'
  ),
  cte2 as (
    select yyyy_mm_dd,  p_id as xml_id, 'payment' as feature,
           case when payment = 1 then 1 else 0 end as status
    from schema.t2
    where yyyy_mm_dd >= '2019-02-02'
  )
select c1.* from cte1 c1
where exists (select 1 from cte2 c2 where c2.yyyy_mm_dd = c1.yyyy_mm_dd)
union all
select c2.* from cte2 c2
where exists (select 1 from cte1 c1 where c1.yyyy_mm_dd = c2.yyyy_mm_dd)

相关问题