-- Databricks notebook source
----------------------------------------------------------------------------
--修改时间：20241126
--修改人：Fanxujia
--修改内容：
--补充THC渠道的全国的事实表中的pack_cod
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--修改时间：20241129
--修改人：Fanxujia
--修改内容：
--补充Retail直取中DTP的手工文件里的pack_cod
----------------------------------------------------------------------------
with external_sales as (
select distinct PACK_CODE AS PACK_COD
from dm.DM_TF_EXT_UNIONALL_SALES
union
select distinct pack_cod
from dm.dm_tf_external_sales_thc
union
select distinct pack_code
from dm.dm_zk_retail_sales_kpi
where NVL(pack_code,'Others') <> 'Others'
and pack_code <> ''
)

--只存放有外部数据的公司信息数据
INSERT OVERWRITE dm.dm_td_external_corp(CORP_COD,CORP_DES,CORP_DES_C,CORP_TYPE)
SELECT A.CORP_COD,CASE WHEN MAX(CORP_DES) LIKE 'ASTRAZENECA%' THEN 'ASTRAZENECA' ELSE MAX(CORP_DES) END CORP_DES,MAX(CORP_DES_C) CORP_DES_C,
CASE WHEN MAX(UPPER(MNFL_DES)) = 'LOCAL' THEN 'LOCAL' 
WHEN UPPER(A.CORP_COD) LIKE '%CORP_COD%' OR UPPER(A.CORP_COD) LIKE '%OTHERS%' THEN ''
ELSE 'MNC' END CORP_TYPE
FROM (select distinct PACK_COD,CORP_COD,CORP_DES,CORP_DES_C,MNFL_DES from DM.dm_td_external_packinfo_temp2) A
INNER JOIN external_sales B ON A.PACK_COD = B.PACK_COD
WHERE A.CORP_COD IS NOT NULL
GROUP BY A.CORP_COD

-- COMMAND ----------


------------ec补充缺少的Corp信息
insert into dm.dm_td_external_corp(CORP_COD,CORP_DES,CORP_DES_C,CORP_TYPE)
select 
  case when CORP_COD is null or CORP_COD = '' then 'CORP_COD_EC(Monthly)'
       else CORP_COD end as CORP_COD,
  max(CORP_DES) CORP_DES,
  max(CORP_DES_C) CORP_DES,
  max(case when upper(MNFL_DES) = 'LOCAL' then 'LOCAL' else 'MNC' end) CORP_TYPE
from dwd.dwd_inc_gnd_retail_b2c_label_total
where CORP_COD in (
  select distinct
    a.CORP_COD
  from (select distinct corp_cod from dm.dm_zk_ec_sales_kpi ) a 
  where not exists(
    select 1 from dm.dm_td_external_corp b 
    where a.CORP_COD = b.CORP_COD
  )
)
group by 1


-- COMMAND ----------


------------Retail补充缺少的Corp信息
insert into dm.dm_td_external_corp(CORP_COD,CORP_DES,CORP_DES_C,CORP_TYPE)
select distinct
  case when CORP_COD is null or CORP_COD = '' then 'CORP_COD_Retail(Quarterly)'
       else CORP_COD end as CORP_COD,
  max(CORP_DES) CORP_DES,
  max(CORP_DES_C) CORP_DES,
  max(case when upper(MNFL_DES) = 'LOCAL' then 'LOCAL' else 'MNC' end) CORP_TYPE
from dwd.dwd_inc_gnd_retail_b2c_label_total
where CORP_COD in (
  select distinct
    a.CORP_COD
  from (select distinct corp_cod from dm.dm_zk_retail_sales_kpi ) a 
  where not exists(
    select 1 from dm.dm_td_external_corp b 
    where a.CORP_COD = b.CORP_COD
  )
)
group by 1
