dwd_dim_user_info_his

用户维度表  

属于拉链表

应用场景:缓慢变化的表

特点:历史数据和最新数据在一张表中

图解:

sql重点:建立临时表,union all , 如何找到并修改旧的end_date,临时表覆盖旧表

insert overwrite table dwd_dim_user_info_his_tmp 
select 
    * 
from 
(
    -- 找出最新信息,
    select 
        id, 
        name, 
        birthday, 
        gender, 
        email,
        user_level, 
        create_time, 
        operate_time, 
        '2020-03-11' start_date, 
        '9999-99-99' end_date 
    from ods_user_info 
    where dt='2020-03-11' 
    
    -- 拼接修改后的旧信息
    union all 
    select 
        uh.id, 
        uh.name, 
        uh.birthday, 
        uh.gender, 
        uh.email, 
        uh.user_level, 
        uh.create_time, 
        uh.operate_time, 
        uh.start_date, 
        -- 与最新数据join ,找出要修改的旧信息,将其期限进行修改
        if(ui.id is not null and uh.end_date='9999-99-99', date_add(ui.dt,-1), uh.end_date) end_date 
    from dwd_dim_user_info_his uh 
    left join 
    ( 
        select 
            * 
        from ods_user_info 
        where dt='2020-03-11' 
    ) ui 
    on uh.id=ui.id 
)his 
order by his.id, start_date;

 覆盖旧表:

insert overwrite table dwd_dim_user_info_his 
select * from dwd_dim_user_info_his_tmp;

回滚:假设回滚至11号,那拉链表的状态得是10号

过滤start_date <= 2020-03-10的数据

将end_date > 2020-03-10的数据

原文地址:https://www.cnblogs.com/ldy233/p/14444260.html