-- Databricks notebook source
-----------------------------------------------------------------------------------
--修改时间：20241021
--修改人：FanXujia
--修改内容：
--只取最新年-1  ~  最新年范围内的，称为“2年共有”。增加
-----------------------------------------------------------------------------------
--共有机构
insert overwrite table dm.dm_aia_hp_flag 
with max_year as (
select
max(cast(year as int)) as max_year,
max(cast(year as int) - 1) as max_year_ly
from dwd.dwd_gnd_hospital_not_provided
)
,hp_flag as (
  select
    distinct concat(t1.year, '-Y') as hp_his_flag,
    case when length(t1.cpa_hospital_code) < 7 then right(concat('0000000',t1.cpa_hospital_code),7) else t1.cpa_hospital_code end as cpa_hospital_code
  from
    dwd.dwd_gnd_hospital_not_provided t1
    cross join max_year t2
    where cast(t1.year as int) >= t2.max_year_ly
)
,hp_flag2 as (
SELECT 
    cpa_hospital_code,
    CONCAT_WS(' ∩ ', SORT_ARRAY(COLLECT_LIST(hp_his_flag))) AS FLAG
FROM 
    hp_flag
GROUP BY 
    cpa_hospital_code
)
,inst_mapping as (
  -- select
  --   distinct right(concat('0000000', org_cd), 7) org_cd,
  --   ins_cd
  -- from
  --   dwd.dwd_gnd_hospitalmapping
select distinct 
case when length(cpa_hospital_code) < 7 then right(concat('0000000',cpa_hospital_code),7) else cpa_hospital_code end as cpa_hospital_code,
ins_cd_nl as inst_code
from dwd.dwd_gnd_hospital_not_provided
)

,ALL_INS as (
select distinct inst_code
from dm.dm_ext_aia_sales
)

,flag as (
  select distinct
    coalesce(t2.inst_code,t1.cpa_hospital_code) as inst_code,
    t1.flag as aia_hp_flag,
    'Y' as FLAG,
'AIA(Monthly)' as DATA_SOURCE
  from hp_flag2 t1
    left join inst_mapping t2 on t1.cpa_hospital_code = t2.cpa_hospital_code
  where
    length(t1.flag) > 6
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'IQVIA-CHPA(Monthly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'XH Data(Quarterly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'EC(Monthly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'Retail(Quarterly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'CHC(Quarterly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'THC(Quarterly)' as DATA_SOURCE
union all
select '' as inst_code,'' as aia_hp_flag,'' as FLAG,'IQVIA-COUNTY(Quarterly)' as DATA_SOURCE
)

select t1.inst_code,
NVL(t2.aia_hp_flag,'') as aia_hp_flag,
NVL(t2.FLAG,'N') as FLAG,
'AIA(Monthly)' as DATA_SOURCE
from ALL_INS t1
left join flag t2
on t1.inst_code = t2.inst_code

