-- Databricks notebook source
-- CREATE OR REPLACE TABLE DM.DM_TD_EXT_AIA_ORG (
--   REGION_CODE STRING,
--   REGION_NAME_EN STRING,
--   RSM_NAME STRING,
--   RC_CODE STRING,
--   RC_NAME_EN STRING,
--   RC_NAME STRING,
--   REGIONCENTER STRING,
--   AUDIT_COD STRING,
--   MARKET STRING,
--   BU_CATEGORY STRING,
--   BU_NAME_EN STRING,
--   SUB_BU_NAME STRING,
--   SUB_BU_CODE_AUTH STRING,
--   BU_CODE_AUTH STRING,
--   DATA_SOURCE STRING,
--   REGION_RATIO FLOAT,
--   TEAM STRING,
--   MR_TRTY_CODE STRING,
--   NSD_KCODE STRING,
--   NSD_NAME STRING,
--   RSD_KCODE STRING,
--   RSD_NAME STRING,
--   RSM_KCODE STRING,
--   DSM_KCODE STRING,
--   DSM_NAME STRING,
--   MR_KCODE STRING,
--   MR_NAME STRING)
-- USING delta
-- LOCATION 'abfss://master@retaildlstoragetest.dfs.core.chinacloudapi.cn/DM/dm_td_ext_aia_org';

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

-- MAGIC %run ../../../Common/config

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

-- MAGIC %python
-- MAGIC spark.read.table(f'`{CDW_CATALOG}`.`dwd`.`dim_product_wide`').createOrReplaceTempView('cdw_dwd_dim_product_wide')

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

-- =============================================================================
-- CELL 1: 临时视图 dm_td_org_temp
-- 背景: 202601 起 EC BU 整体迁移至 Retail，需对历史字段做统一转换，
--       避免下游 CTE 中重复写 CASE WHEN。
-- 修改时间: 20260130
-- =============================================================================
-- COMMAND ----------

CREATE OR REPLACE TEMPORARY VIEW dm_td_org_temp AS
SELECT
    org_key,
    mr_trty_tag,
    district_code,
    district_name,
    rc_name,
    region_name,
    REGION_CODE,
    rc_code,
    bu_category,
    rsm_kcode,
    rsm_name,
    rsd_kcode,
    rsd_name,
    mr_kcode,
    mr_name,
    dsm_kcode,
    dsm_name,
    dsm_trty_code,
    rsm_trty_code,
    rsd_trty_code,
    mr_trty_code,
    yyyymm,

    -- ----------------------------------------------------------------
    -- EC → Retail 字段映射（202601 起生效）
    -- ----------------------------------------------------------------
    CASE WHEN yyyymm >= '202601' AND bu_code    = 'PC12'       THEN 'PC09'       ELSE bu_code       END AS bu_code,
    CASE WHEN yyyymm >= '202601' AND bu_report  = 'EC'         THEN 'Retail'     ELSE bu_report     END AS bu_report,
    CASE WHEN yyyymm >= '202601' AND sub_bu_code = 'NA27'      THEN 'NA06'       ELSE sub_bu_code   END AS sub_bu_code,
    CASE WHEN yyyymm >= '202601' AND sub_bu_name = 'EC'        THEN 'Retail'     ELSE sub_bu_name   END AS sub_bu_name,
    CASE WHEN yyyymm >= '202601' AND sub_bu_name_en = 'EC'     THEN 'Retail'     ELSE sub_bu_name_en END AS sub_bu_name_en,
    CASE WHEN yyyymm >= '202601' AND bu_name    = 'EC'         THEN 'Retail'     ELSE bu_name       END AS bu_name,
    CASE WHEN yyyymm >= '202601' AND bu_name_en = 'EC'         THEN 'Retail'     ELSE bu_name_en    END AS bu_name_en,
    CASE WHEN yyyymm >= '202601' AND nsd_kcode  = 'ND_EC0001_V' THEN 'KSGX559'   ELSE nsd_kcode     END AS nsd_kcode,
    CASE WHEN yyyymm >= '202601' AND bu_name    = 'EC'
          AND nsd_name = 'Vacant'                              THEN '李白杨'      ELSE nsd_name      END AS nsd_name,
    CASE WHEN yyyymm >= '202601' AND nsd_trty_code = 'ND_EC0001' THEN 'ND_RT0001' ELSE nsd_trty_code END AS nsd_trty_code,
    CASE WHEN yyyymm >= '202601' AND bsd_kcode  = 'VP_EC0001_V' THEN 'VP_RT0001_V' ELSE bsd_kcode   END AS bsd_kcode,
    CASE WHEN yyyymm >= '202601' AND bsd_trty_code = 'VP_EC0001' THEN 'VP_RT0001'  ELSE bsd_trty_code END AS bsd_trty_code

FROM DM.dm_td_org

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

-- ---------------------------------------------------------------------------------------
-- --修改时间：20241105
-- --修改人：Fanxujia
-- --修改内容：
-- --for AIA Dashboard，新增NSD、RSD、RSM、DSM、MR、TEAM等信息
-- --仅AIA渠道的数据增加值，其他渠道都为空
-- ---------------------------------------------------------------------------------------
-- ---------------------------------------------------AIA------------------------------------------------------------------------------
-- --AIA参考CHPA
-- ------所有BU能看AIA

-- --从销量表取到全部的机构、市场组合
-- with ALL_AUDIT_Market as (
-- select distinct NVL(t1.AUDIT_COD,'ROC') AUDIT_COD,
-- NVL(t2.market,'ALL Market') market
-- from dm.dm_ext_aia_sales t1
-- left join dm.dm_td_ext_aia_market_pack_mapping t2
-- on t1.pack_cod = t2.PACK_CODE
-- )
-- ,pack_market as (
-- select distinct PACK_CODE AS PACK_COD,market
-- from dm.dm_td_ext_aia_market_pack_mapping
-- )

-- --获取城市与大区中心的mapping
-- ,EXTERNAL_GEO as (
-- select distinct
-- concat(city_c, '市') as city_c,
-- REGION_CENTER
-- from DM.DM_TD_EXTERNAL_GEO_TEMP
-- where DATA_SOURCE = 'AIA(Monthly)'
-- )
-- --CVH架构月
-- ,CVH_YM as (
-- select key_value as yyyymm
-- from dm.dm_td_date_config
-- where key_code = 'pfmc_cvh'
-- )
-- --org表
-- ,org as (
-- select distinct
-- t1.yyyymm,
-- t1.bu_category,
-- t1.bu_code,
-- t1.bu_name_en,
-- t1.sub_bu_code,
-- t1.sub_bu_name,
-- t1.REGION_CODE,
-- t1.region_name,
-- t1.rc_code,
-- t1.rc_name,
-- t1.district_name as team,
-- t1.mr_trty_code,
-- t1.nsd_kcode,
-- case when t1.nsd_name = 'Vacant' then t1.nsd_kcode else t1.nsd_name end as nsd_name,
-- t1.rsd_kcode,
-- case when t1.rsd_name = 'Vacant' then t1.rsd_kcode else t1.rsd_name end as rsd_name,
-- t1.rsm_kcode,
-- case when t1.rsm_name = 'Vacant' then t1.rsm_kcode else t1.rsm_name end as rsm_name,
-- t1.dsm_kcode,
-- case when t1.dsm_name = 'Vacant' then t1.dsm_kcode else t1.dsm_name end as dsm_name,
-- t1.mr_kcode,
-- case when t1.mr_name = 'Vacant' then t1.mr_kcode else t1.mr_name end as mr_name
-- from dm_td_org_temp t1
-- inner join CVH_YM t2
-- on t1.yyyymm = t2.yyyymm
-- )
-- --territory表
-- ,territory as (
-- select distinct
-- t1.yyyymm,
-- t1.trty_code,
-- t1.inst_code,
-- t1.family_code
-- from dm.dm_td_sd_territory_indication t1
-- inner join CVH_YM t2
-- on t1.yyyymm = t2.yyyymm
-- where t1.bu not in ('CUBE','KA')
-- and ((t1.key_hp in (2) and t1.bu <> 'Retail' and t1.trty_code <>'Eagle') or t1.key_hp = 1)--chenwu 20250904 排除双考影响
-- )
-- --将内部的Family_code转为外部的pack_cod
-- ,inst_pack_previous as (
-- select distinct
-- t1.yyyymm,
-- t1.trty_code,
-- t1.inst_code,
-- t2.city_name,
-- t5.market,
-- case when t2.area_code = 'SOUTH' then 'South'
--      when t2.area_code = 'WEST' then 'West'
-- 		 when t2.area_code = 'CENTRAL' then 'Central'
-- 		 when t2.area_code = 'NORTH' then 'North'
-- 		 when t2.area_code = 'EAST' then 'East'
-- end as REGION_CENTER
-- from territory t1
-- left join dwd.dwd_td_institution t2
-- on t1.inst_code = t2.inst_code
-- left join cdw_dwd_dim_product_wide t3
-- on t1.family_code = t3.prd_family_cd
-- left join dwd.dwd_td_imscode_azcode t4
-- on t3.prd_brand_cd = t4.brandcode
-- left join pack_market t5
-- on t4.ims_pack_cod = t5.PACK_COD
-- )
-- /*
-- 20251207 Chenwu 把可定的架构复制到立普妥上,直接替换市场 'Atorvastatin Market' = 'Rosuvastatin Market'
-- */
-- ,inst_pack as (
--   select 
--     yyyymm,
--     trty_code,
--     inst_code,
--     city_name,
--     market,
--     REGION_CENTER
--   from inst_pack_previous
--   union all
--   select
--     yyyymm,
--     trty_code,
--     inst_code,
--     city_name,
--     'Atorvastatin Market' market,
--     REGION_CENTER
--   from inst_pack_previous 
--   where market = 'Rosuvastatin Market'
-- )

-- ---------------------------------------------------------------------------------------
-- --修改时间：20250220
-- --修改人：Zhu chenwu
-- --修改内容：
-- --原本存在部分Eagel的机构和市场没有挂上架构，针对于没有挂上的部分，用dws.dws_td_eg_cityterritory中的city 和family的关系对应到市场挂上架构。
-- ----------------------------------------------m-----------------------------------------
-- ,eagle_trty as 
-- (---eagle的city 和 family 对应的 trtycode取数据时，如果city和family对应的trtycode 有多个，以p12，p11,p11为准，取第一个。
--   select SP_TRTY_CD,CITY_CD,FAMILY_CD from (
--   select *
--   ,row_number() over (partition by CITY_CD,FAMILY_CD order by PROJECT_CD desc) as num
--   from (
--     select SP_TRTY_CD,CITY_CD,FAMILY_CD,PROJECT_CD  from  dws.dws_td_eg_cityterritory t1 
--     inner join CVH_YM t2
--     on t1.YM = t2.yyyymm
--     where SP_TRTY_CD not in (select distinct trty_code from dm.dm_td_sd_territory_indication where bu = 'Eagle')
--     and PROJECT_CD in (select distinct project_code from DWS.dws_td_eg_project_instype WHERE ins_type='医院') 
--     and cast(nvl(SALES_RATE,0) as decimal(20,6))<>'0.000000' 
--     group by  1,2,3,4
--   )
-- ) where num = 1
-- )
-- ,family_mapping as (--family和brand的mapping
--   select prd_family_cd,prd_brand_cd from cdw_dwd_dim_product_wide
--   group by 1,2
-- )
-- ,packcode_mapping as (--pack 和 brand的mapping
--   select brandcode,ims_pack_cod from dwd.dwd_td_imscode_azcode 
--   group by 1,2
-- )
-- ,geo_mapping as (--city的中文
--   select city_code,city_name from dm.dm_td_geography
--   group by 1,2
-- )
-- ,eagle_mapping (--eagle表中city和family所对应的 岗位编码
-- select SP_TRTY_CD,city_name,market from (
-- 	select 
-- 	t1.SP_TRTY_CD
-- 	-- ,t1.FAMILY_CD
-- 	-- ,t3.prd_brand_cd
-- 	,t4.ims_pack_cod
-- 	,t5.city_name
-- 	from eagle_trty t1
-- 	left join family_mapping t3
-- 	on t1.FAMILY_CD = t3.prd_family_cd --转换family 成 brand
-- 	left join packcode_mapping t4
-- 	on t3.prd_brand_cd = t4.brandcode
-- 	left join geo_mapping t5
-- 	on t1.CITY_CD = t5.city_code) A
-- inner join pack_market B on A.ims_pack_cod = B.PACK_COD
-- group by 1,2,3
-- )

-- ,audit_geo as (--audit的城市信息
-- select AUDIT_COD,max(CITY_C) as city_c from DM.DM_TD_EXTERNAL_GEO 
-- where DATA_SOURCE = 'AIA(Monthly)'
-- group by 1)

-- ,eagle_trty_with_city as ( --eagle中 挂上 部分机构归不到eagle的，按eagle的城市+品牌挂上
-- select
-- t0.AUDIT_COD,t0.market
-- ,t10.city_c
-- ,eagle_mapping.SP_TRTY_CD from ALL_AUDIT_Market t0
-- left join audit_geo t10 on t0.AUDIT_COD = t10.AUDIT_COD
-- left join eagle_mapping on eagle_mapping.city_name = t10.city_c and eagle_mapping.market = t0.market 
-- where eagle_mapping.SP_TRTY_CD is not null
-- group by 1,2,3,4)

-- insert overwrite dm.DM_TD_EXT_AIA_ORG (
--     REGION_CODE,
--     region_name_en,
--     rc_code,
--     rc_name_en,
--     RegionCenter,
--     AUDIT_COD,
--     MARKET,
--     bu_category,
--     bu_name_en,
--     sub_bu_name,
--     sub_bu_code_auth,
--     bu_code_auth,
--     DATA_SOURCE,
--     REGION_RATIO,
--     RSM_Name,
--     RC_Name,
-- TEAM,
-- MR_TRTY_CODE,
-- NSD_KCODE,
-- NSD_NAME,
-- RSD_KCODE,
-- RSD_NAME,
-- RSM_KCODE,
-- DSM_KCODE,
-- DSM_NAME,
-- MR_KCODE,
-- MR_NAME
--   )

-- SELECT distinct
--   COALESCE(t2.REGION_CODE,t6.REGION_CODE,'ROC') as REGION_CODE,
--   COALESCE(t2.region_name,t6.region_name,'ROC') as region_name_en,
--   COALESCE(t2.rc_code,t6.rc_code,'ROC') as rc_code,
--   COALESCE(t2.rc_name,t6.rc_name,'ROC') as rc_name_en,
--   COALESCE(t1.REGION_CENTER,t4.REGION_CENTER,t7.REGION_CENTER,'') as RegionCenter,
--   t0.AUDIT_COD,
--   t0.MARKET,
--   COALESCE(t2.bu_category,t6.bu_category,'') as bu_category,
--   COALESCE(t2.bu_name_en,t6.bu_name_en,'') as bu_name_en,
--   COALESCE(t2.sub_bu_name,t6.sub_bu_name,'') as sub_bu_name,
--   COALESCE(t2.sub_bu_code,t6.sub_bu_code,'') as sub_bu_code_auth,
--   concat(COALESCE(t2.bu_code,t6.bu_code,''),'AIA(Monthly)') as bu_code_auth,
--   'AIA(Monthly)' as DATA_SOURCE,
--   1 REGION_RATIO,
--   COALESCE(t2.rsm_name,t6.rsm_name,'Vacant') as rsm_name,
--   COALESCE(t2.rsd_name,t6.rsd_name,'Vacant') as RC_Name,
--   COALESCE(t2.team,t6.team,'ROC') as team,
--   COALESCE(t2.mr_trty_code,t6.mr_trty_code,'Vacant') as mr_trty_code,
--   COALESCE(t2.nsd_kcode,t6.nsd_kcode,'Vacant') as nsd_kcode,
--   COALESCE(t2.nsd_name,t6.nsd_name,'Vacant') as nsd_name,
--   COALESCE(t2.rsd_kcode,t6.rsd_kcode,'Vacant') as rsd_kcode,
--   COALESCE(t2.rsd_name,t6.rsd_name,'Vacant') as rsd_name,
--   COALESCE(t2.rsm_kcode,t6.rsm_kcode,'Vacant') as rsm_kcode,
--   COALESCE(t2.dsm_kcode,t6.dsm_kcode,'Vacant') as dsm_kcode,
--   COALESCE(t2.dsm_name,t6.dsm_name,'Vacant') as dsm_name,
--   COALESCE(t2.mr_kcode,t6.mr_kcode,'Vacant') as mr_kcode,
--   COALESCE(t2.mr_name,t6.mr_name,'Vacant') as mr_name
-- -- ,t5.SP_TRTY_CD
-- from ALL_AUDIT_Market t0
-- left join inst_pack t1
-- on t0.AUDIT_COD = t1.inst_code
-- and t0.market = t1.market
-- left join org t2
-- on t1.trty_code = t2.mr_trty_code
-- and t1.yyyymm = t2.yyyymm
-- left join EXTERNAL_GEO t4
-- on t1.city_name = t4.city_c

-- left join eagle_trty_with_city t5
-- on t0.AUDIT_COD = t5.AUDIT_COD
-- and t0.market = t5.market and t1.inst_code is null
-- left join org t6
-- on t5.SP_TRTY_CD = t6.mr_trty_code
-- left join EXTERNAL_GEO t7
-- on t5.city_c = t7.city_c

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

WITH

-- ----------------------------------------------------------------------------
-- [基础配置] CVH 考核月份白名单
-- ----------------------------------------------------------------------------
cvh_ym AS (
    SELECT key_value AS yyyymm
    FROM   dm.dm_td_date_config
    WHERE  key_code = 'pfmc_cvh'
),

-- ----------------------------------------------------------------------------
-- [输入数据] 事实表中所有有效的 机构×市场 组合（作为主驱动集合）
-- ----------------------------------------------------------------------------
all_audit_market AS (
    SELECT DISTINCT
        NVL(s.AUDIT_COD, 'ROC')       AS audit_cod,
        NVL(m.market,   'ALL Market') AS market
    FROM   dm.dm_ext_aia_sales             s
    LEFT JOIN dm.dm_td_ext_aia_market_pack_mapping m
           ON s.pack_cod = m.PACK_CODE
),

-- ----------------------------------------------------------------------------
-- [参照表] Pack → Market 映射
-- ----------------------------------------------------------------------------
pack_market AS (
    SELECT DISTINCT
        PACK_CODE AS pack_cod,
        market
    FROM dm.dm_td_ext_aia_market_pack_mapping
),

-- ----------------------------------------------------------------------------
-- [参照表] 城市 → 大区中心映射（AIA 渠道）
-- ----------------------------------------------------------------------------
external_geo AS (
    SELECT DISTINCT
        CONCAT(city_c, '市') AS city_c,
        REGION_CENTER
    FROM DM.DM_TD_EXTERNAL_GEO_TEMP
    WHERE DATA_SOURCE = 'AIA(Monthly)'
),

-- ----------------------------------------------------------------------------
-- [内部组织] CVH 月份范围内的 org 层级数据
-- Vacant 岗位用 kcode 替代，便于前端展示
-- ----------------------------------------------------------------------------
org AS (
    SELECT DISTINCT
        o.yyyymm,
        o.bu_category,
        o.bu_code,
        o.bu_name_en,
        o.sub_bu_code,
        o.sub_bu_name,
        o.REGION_CODE,
        o.region_name,
        o.rc_code,
        o.rc_name,
        o.district_name                                                       AS team,
        o.mr_trty_code,
        o.nsd_kcode,
        CASE WHEN o.nsd_name = 'Vacant' THEN o.nsd_kcode ELSE o.nsd_name END AS nsd_name,
        o.rsd_kcode,
        CASE WHEN o.rsd_name = 'Vacant' THEN o.rsd_kcode ELSE o.rsd_name END AS rsd_name,
        o.rsm_kcode,
        CASE WHEN o.rsm_name = 'Vacant' THEN o.rsm_kcode ELSE o.rsm_name END AS rsm_name,
        o.dsm_kcode,
        CASE WHEN o.dsm_name = 'Vacant' THEN o.dsm_kcode ELSE o.dsm_name END AS dsm_name,
        o.mr_kcode,
        CASE WHEN o.mr_name  = 'Vacant' THEN o.mr_kcode  ELSE o.mr_name  END AS mr_name
    FROM  dm_td_org_temp o
    INNER JOIN cvh_ym    c ON o.yyyymm = c.yyyymm
),

-- ----------------------------------------------------------------------------
-- [正常路径 1/3] CVH 月份范围内的 Territory 指示表
-- 排除 CUBE、KA；双考场景仅保留 key_hp=1 或非 Eagle 的 key_hp=2 记录
-- 修改: chenwu 20250904
-- ----------------------------------------------------------------------------
territory AS (
    SELECT DISTINCT
        t.yyyymm,
        t.trty_code,
        t.inst_code,
        t.family_code
    FROM   dm.dm_td_sd_territory_indication t
    INNER JOIN cvh_ym c ON t.yyyymm = c.yyyymm
    WHERE  t.bu NOT IN ('CUBE', 'KA')
      AND  (
               (t.key_hp = 2 AND t.bu <> 'Retail' AND t.trty_code <> 'Eagle')
            OR  t.key_hp = 1
           )
),

-- ----------------------------------------------------------------------------
-- [正常路径 2/3] Territory → 机构 → 城市 → 市场 映射
-- family_code 经 product_wide → imscode_azcode → pack_market 三跳转换
-- ----------------------------------------------------------------------------
inst_pack_base AS (
    SELECT DISTINCT
        t.yyyymm,
        t.trty_code,
        t.inst_code,
        i.city_name,
        pm.market,
        CASE i.area_code
            WHEN 'SOUTH'   THEN 'South'
            WHEN 'WEST'    THEN 'West'
            WHEN 'CENTRAL' THEN 'Central'
            WHEN 'NORTH'   THEN 'North'
            WHEN 'EAST'    THEN 'East'
        END AS region_center
    FROM   territory                   t
    LEFT JOIN dwd.dwd_td_institution   i  ON t.inst_code    = i.inst_code
    LEFT JOIN cdw_dwd_dim_product_wide p  ON t.family_code  = p.prd_family_cd
    LEFT JOIN dwd.dwd_td_imscode_azcode az ON p.prd_brand_cd = az.brandcode
    LEFT JOIN pack_market              pm ON az.ims_pack_cod = pm.pack_cod
),

-- [正常路径 3/3] 可定架构（Rosuvastatin Market）复制到立普妥（Atorvastatin Market）
-- 修改: Chenwu 20251207
inst_pack AS (
    SELECT * FROM inst_pack_base
    UNION ALL
    SELECT yyyymm, trty_code, inst_code, city_name,
           'Atorvastatin Market' AS market,
           region_center
    FROM   inst_pack_base
    WHERE  market = 'Rosuvastatin Market'
),

-- ============================================================================
-- [Eagle 回退路径] 部分机构未能通过正常 territory 路径挂上架构，
--                 改用 城市+品牌 关系匹配 Eagle territory code
-- 修改: Chenwu 20250220
-- ============================================================================

-- Eagle: city × family → territory code（多个时取 PROJECT_CD 最大者）
eagle_trty AS (
    SELECT SP_TRTY_CD, CITY_CD, FAMILY_CD
    FROM (
        SELECT
            SP_TRTY_CD, CITY_CD, FAMILY_CD,
            ROW_NUMBER() OVER (PARTITION BY CITY_CD, FAMILY_CD ORDER BY PROJECT_CD DESC) AS rn
        FROM (
            SELECT eg.SP_TRTY_CD, eg.CITY_CD, eg.FAMILY_CD, eg.PROJECT_CD
            FROM   dws.dws_td_eg_cityterritory        eg
            INNER JOIN cvh_ym                          c  ON eg.YM = c.yyyymm
            -- 仅保留非 Eagle BU 已覆盖的 territory（Anti-Join，性能优于 NOT IN 子查询）
            LEFT  JOIN (
                SELECT DISTINCT trty_code
                FROM dm.dm_td_sd_territory_indication
                WHERE bu = 'Eagle'
            )                                          ex ON eg.SP_TRTY_CD = ex.trty_code
            -- 仅医院类项目
            INNER JOIN (
                SELECT DISTINCT project_code
                FROM DWS.dws_td_eg_project_instype
                WHERE ins_type = '医院'
            )                                          pi ON eg.PROJECT_CD = pi.project_code
            WHERE  ex.trty_code IS NULL                   -- Anti-Join 条件
              AND  NVL(eg.SALES_RATE, 0) <> 0             -- 排除零销售比例（原逻辑：cast <> '0.000000'）
            GROUP BY eg.SP_TRTY_CD, eg.CITY_CD, eg.FAMILY_CD, eg.PROJECT_CD
        ) base
    ) deduped
    WHERE rn = 1
),

-- Eagle territory → 市场 映射（family → brand → pack → market，city code → city name）
eagle_mapping AS (
    SELECT
        et.SP_TRTY_CD,
        g.city_name,
        pm.market
    FROM   eagle_trty                   et
    LEFT JOIN cdw_dwd_dim_product_wide  p  ON et.FAMILY_CD    = p.prd_family_cd
    LEFT JOIN dwd.dwd_td_imscode_azcode az ON p.prd_brand_cd  = az.brandcode
    LEFT JOIN dm.dm_td_geography        g  ON et.CITY_CD      = g.city_code
    INNER JOIN pack_market              pm ON az.ims_pack_cod  = pm.pack_cod
    GROUP BY et.SP_TRTY_CD, g.city_name, pm.market
),

-- Audit 机构 → 城市 映射
audit_geo AS (
    SELECT   AUDIT_COD, MAX(CITY_C) AS city_c
    FROM     DM.DM_TD_EXTERNAL_GEO
    WHERE    DATA_SOURCE = 'AIA(Monthly)'
    GROUP BY AUDIT_COD
),

-- 汇总：对 all_audit_market 中无法通过 inst_pack 匹配的记录，
-- 尝试用 Eagle 城市+市场 回退挂上 territory code
eagle_trty_with_city AS (
    SELECT
        am.AUDIT_COD,
        am.market,
        ag.city_c,
        em.SP_TRTY_CD
    FROM   all_audit_market am
    LEFT JOIN audit_geo      ag ON am.AUDIT_COD  = ag.AUDIT_COD
    LEFT JOIN eagle_mapping  em ON em.city_name  = ag.city_c
                                AND em.market     = am.market
    WHERE  em.SP_TRTY_CD IS NOT NULL   -- 仅保留能匹配到 Eagle territory 的行
    GROUP BY am.AUDIT_COD, am.market, ag.city_c, em.SP_TRTY_CD
)

-- ----------------------------------------------------------------------------
-- 主写入：覆盖写目标表
-- 优先级: t2（正常路径 org）> t6（Eagle 回退 org）> 硬编码默认值
-- ----------------------------------------------------------------------------
INSERT OVERWRITE dm.DM_TD_EXT_AIA_ORG (
    REGION_CODE, region_name_en,
    rc_code,     rc_name_en,
    RegionCenter,
    AUDIT_COD,   MARKET,
    bu_category, bu_name_en,
    sub_bu_name, sub_bu_code_auth, bu_code_auth,
    DATA_SOURCE, REGION_RATIO,
    RSM_Name,    RC_Name,    TEAM,
    MR_TRTY_CODE,
    NSD_KCODE,   NSD_NAME,
    RSD_KCODE,   RSD_NAME,
    RSM_KCODE,
    DSM_KCODE,   DSM_NAME,
    MR_KCODE,    MR_NAME
)
SELECT DISTINCT
    COALESCE(t2.REGION_CODE,  t6.REGION_CODE,  'ROC') AS REGION_CODE,
    COALESCE(t2.region_name,  t6.region_name,  'ROC') AS region_name_en,
    COALESCE(t2.rc_code,      t6.rc_code,      'ROC') AS rc_code,
    COALESCE(t2.rc_name,      t6.rc_name,      'ROC') AS rc_name_en,
    COALESCE(t1.region_center, t4.REGION_CENTER, t7.REGION_CENTER, '') AS RegionCenter,
    t0.audit_cod,
    t0.market,
    COALESCE(t2.bu_category,  t6.bu_category,  '')        AS bu_category,
    COALESCE(t2.bu_name_en,   t6.bu_name_en,   '')        AS bu_name_en,
    COALESCE(t2.sub_bu_name,  t6.sub_bu_name,  '')        AS sub_bu_name,
    COALESCE(t2.sub_bu_code,  t6.sub_bu_code,  '')        AS sub_bu_code_auth,
    CONCAT(COALESCE(t2.bu_code, t6.bu_code, ''), 'AIA(Monthly)') AS bu_code_auth,
    'AIA(Monthly)'                                        AS DATA_SOURCE,
    1                                                     AS REGION_RATIO,
    COALESCE(t2.rsm_name,     t6.rsm_name,     'Vacant') AS RSM_Name,
    COALESCE(t2.rsd_name,     t6.rsd_name,     'Vacant') AS RC_Name,
    COALESCE(t2.team,         t6.team,         'ROC')    AS TEAM,
    COALESCE(t2.mr_trty_code, t6.mr_trty_code, 'Vacant') AS MR_TRTY_CODE,
    COALESCE(t2.nsd_kcode,    t6.nsd_kcode,    'Vacant') AS NSD_KCODE,
    COALESCE(t2.nsd_name,     t6.nsd_name,     'Vacant') AS NSD_NAME,
    COALESCE(t2.rsd_kcode,    t6.rsd_kcode,    'Vacant') AS RSD_KCODE,
    COALESCE(t2.rsd_name,     t6.rsd_name,     'Vacant') AS RSD_NAME,
    COALESCE(t2.rsm_kcode,    t6.rsm_kcode,    'Vacant') AS RSM_KCODE,
    COALESCE(t2.dsm_kcode,    t6.dsm_kcode,    'Vacant') AS DSM_KCODE,
    COALESCE(t2.dsm_name,     t6.dsm_name,     'Vacant') AS DSM_NAME,
    COALESCE(t2.mr_kcode,     t6.mr_kcode,     'Vacant') AS MR_KCODE,
    COALESCE(t2.mr_name,      t6.mr_name,      'Vacant') AS MR_NAME
FROM all_audit_market t0
-- ── 正常路径 ──────────────────────────────────────────────────────────────
LEFT JOIN inst_pack      t1 ON  t0.audit_cod = t1.inst_code
                            AND t0.market    = t1.market
LEFT JOIN org            t2 ON  t1.trty_code = t2.mr_trty_code
                            AND t1.yyyymm    = t2.yyyymm
LEFT JOIN external_geo   t4 ON  t1.city_name = t4.city_c
-- ── Eagle 回退路径（仅当正常路径未能匹配机构时） ──────────────────────────
LEFT JOIN eagle_trty_with_city t5 ON  t0.audit_cod  = t5.AUDIT_COD
                                  AND t0.market     = t5.market
                                  AND t1.inst_code IS NULL   -- 正常路径未命中
LEFT JOIN org            t6 ON  t5.SP_TRTY_CD = t6.mr_trty_code
LEFT JOIN external_geo   t7 ON  t5.city_c     = t7.city_c

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

-- --修改时间：20240808
-- --修改人：FanXuJia
-- --修改背景：
-- --事实表与维度表来自于不同手工表，目前存在一部分audit_cod在事实表有销量，但是在维度表没有这个audit_cod，导致销量缺失。
-- --因此需要从事实表补全这部分audit_cod
-- with sales as (
-- select distinct PACK_COD,AUDIT_COD,DATA_SOURCE from dm.dm_tf_external_sales
-- union
-- select distinct PACK_COD,AUDIT_COD,DATA_SOURCE from dm.dm_tf_external_sales_thc
-- )
-- ,market_pack as (
-- select distinct PACK_COD,MARKET,DATA_SOURCE from dm.dm_td_external_market_pack_mapping
-- )
-- ,org as (
-- select distinct AUDIT_COD,MARKET,DATA_SOURCE from dm.DM_TD_EXT_AIA_ORG
-- )
-- ,tmp_org as (
-- select distinct a.AUDIT_COD,b.MARKET,a.DATA_SOURCE
-- from sales a 
-- left join market_pack b on a.PACK_COD = b.PACK_COD and a.DATA_SOURCE = b.DATA_SOURCE
-- left join org c on a.DATA_SOURCE = c.DATA_SOURCE and a.AUDIT_COD = c.AUDIT_COD and b.MARKET = c.MARKET
-- where C.AUDIT_COD IS NULL
-- )
-- insert into table dm.DM_TD_EXT_AIA_ORG
-- (
-- REGION_CODE,
-- region_name_en,
-- RSM_Name,
-- rc_code,
-- rc_name_en,
-- RC_Name,
-- RegionCenter,
-- AUDIT_COD,
-- MARKET,
-- bu_category,
-- bu_name_en,
-- sub_bu_name,
-- sub_bu_code_auth,
-- bu_code_auth,
-- DATA_SOURCE,
-- REGION_RATIO,
-- TEAM,
-- MR_TRTY_CODE,
-- NSD_KCODE,
-- NSD_NAME,
-- RSD_KCODE,
-- RSD_NAME,
-- RSM_KCODE,
-- DSM_KCODE,
-- DSM_NAME,
-- MR_KCODE,
-- MR_NAME
-- )
-- select
-- 'ROC' as REGION_CODE,
-- 'ROC' as region_name_en,
-- 'Vacant' as RSM_Name,
-- 'ROC' as rc_code,
-- 'ROC' as rc_name_en,
-- 'Vacant' as RC_Name,
-- null as RegionCenter,
-- AUDIT_COD,
-- MARKET,
-- null as bu_category,
-- null as bu_name_en,
-- null as sub_bu_name,
-- null as sub_bu_code_auth,
-- DATA_SOURCE as bu_code_auth,
-- DATA_SOURCE,
-- 1 as REGION_RATIO,
-- 'ROC' as TEAM,
-- 'Vacant' as MR_TRTY_CODE,
-- 'Vacant' as NSD_KCODE,
-- 'Vacant' as NSD_NAME,
-- 'Vacant' as RSD_KCODE,
-- 'Vacant' as RSD_NAME,
-- 'Vacant' as RSM_KCODE,
-- 'Vacant' as DSM_KCODE,
-- 'Vacant' as DSM_NAME,
-- 'Vacant' as MR_KCODE,
-- 'Vacant' as MR_NAME
-- from tmp_org
-- where DATA_SOURCE = 'AIA(Monthly)'

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

-- DBTITLE 1,add
-- =============================================================================
-- CELL 3: INSERT INTO —— 补全缺失机构（Backfill）
--
-- 背景: 事实表（dm_tf_external_sales / _thc）与维度表来自不同手工文件，
--       部分 audit_cod 有销量但维度表中缺失，导致前端漏数。
--       此步骤找出差集并以默认值兜底写入。
-- 修改时间: 20240808  修改人: FanXuJia
-- =============================================================================
-- COMMAND ----------

WITH
-- 提前过滤 AIA 渠道，减少后续 JOIN 数据量
aia_sales AS (
    SELECT PACK_CODE, AUDIT_CODE
    FROM dm.dm_tf_ext_aia_sales
),
pack_market_ref AS (
    SELECT DISTINCT PACK_CODE, MARKET
    FROM   dm.dm_td_ext_aia_market_pack_mapping
    -- WHERE  DATA_SOURCE = 'AIA(Monthly)'
),
existing_org AS (
    SELECT DISTINCT AUDIT_COD, MARKET
    FROM   dm.DM_TD_EXT_AIA_ORG
    WHERE  DATA_SOURCE = 'AIA(Monthly)'
),
-- 找出：有销量 但 维度表中没有的 audit_cod × market 组合
missing_org AS (
    SELECT DISTINCT
        s.AUDIT_CODE,
        m.MARKET
    FROM   aia_sales      s
    LEFT JOIN pack_market_ref m ON s.PACK_CODE  = m.PACK_CODE
    LEFT JOIN existing_org    e ON s.AUDIT_CODE = e.AUDIT_COD
                               AND m.MARKET    = e.MARKET
    WHERE  e.AUDIT_COD IS NULL     -- Anti-Join: 维度表中不存在
      AND  m.MARKET    IS NOT NULL  -- 排除无法映射到市场的包装
)

INSERT INTO TABLE dm.DM_TD_EXT_AIA_ORG (
    REGION_CODE, region_name_en,
    RSM_Name,    rc_code,     rc_name_en, RC_Name,  RegionCenter,
    AUDIT_COD,   MARKET,
    bu_category, bu_name_en,  sub_bu_name, sub_bu_code_auth, bu_code_auth,
    DATA_SOURCE, REGION_RATIO,
    TEAM,
    MR_TRTY_CODE,
    NSD_KCODE,   NSD_NAME,
    RSD_KCODE,   RSD_NAME,
    RSM_KCODE,
    DSM_KCODE,   DSM_NAME,
    MR_KCODE,    MR_NAME
)
SELECT
    'ROC'           AS REGION_CODE,
    'ROC'           AS region_name_en,
    'Vacant'        AS RSM_Name,
    'ROC'           AS rc_code,
    'ROC'           AS rc_name_en,
    'Vacant'        AS RC_Name,
    NULL            AS RegionCenter,
    AUDIT_CODE,
    MARKET,
    NULL            AS bu_category,
    NULL            AS bu_name_en,
    NULL            AS sub_bu_name,
    NULL            AS sub_bu_code_auth,
    'AIA(Monthly)'  AS bu_code_auth,
    'AIA(Monthly)'  AS DATA_SOURCE,
    1               AS REGION_RATIO,
    'ROC'           AS TEAM,
    'Vacant'        AS MR_TRTY_CODE,
    'Vacant'        AS NSD_KCODE,
    'Vacant'        AS NSD_NAME,
    'Vacant'        AS RSD_KCODE,
    'Vacant'        AS RSD_NAME,
    'Vacant'        AS RSM_KCODE,
    'Vacant'        AS DSM_KCODE,
    'Vacant'        AS DSM_NAME,
    'Vacant'        AS MR_KCODE,
    'Vacant'        AS MR_NAME
FROM missing_org


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

-- -----------------------------------------------------------
-- --修改时间：20241118
-- --修改人：Fanxujia
-- --修改内容：
-- --使用手工文件排除掉每个渠道的不需要显示的市场
-- -----------------------------------------------------------
-- with hidden_market as (
-- select distinct 
-- case when upper(data_source) = 'CHPA'    then 'IQVIA-CHPA(Monthly)'
--      when upper(data_source) = '科室市场' then 'XH Data(Quarterly)'
--      when upper(data_source) = 'EC'      then 'EC(Monthly)'
--      when upper(data_source) = 'RETAIL'  then 'Retail(Quarterly)'
--      when upper(data_source) = 'CHC'     then 'CHC(Quarterly)'
--      when upper(data_source) = 'AIA'     then 'AIA(Monthly)'
--      when upper(data_source) = 'THC'     then 'THC(Quarterly)'
--      when upper(data_source) = 'COUNTY'  then 'IQVIA-COUNTY(Quarterly)'
--      else data_source
-- end as data_source,
-- upper(hidden_market) as hidden_market
-- from dwd.dwd_gnd_ims_hidden_market
-- union all 
-- select
-- 'AIA(Monthly)' as data_source,
-- 'AIA ALL Market'
-- )


-- MERGE into dm.DM_TD_EXT_AIA_ORG as t1
-- USING hidden_market t2
-- on t1.data_source = t2.data_source
-- and upper(t1.MARKET) = upper(t2.hidden_market)
-- WHEN MATCHED THEN
-- DELETE

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

-- DBTITLE 1,hidden_market
-- =============================================================================
-- CELL 4: MERGE DELETE —— 按隐藏市场规则清理不展示的行
--
-- 背景: 通过手工文件 dwd_gnd_ims_hidden_market 维护各渠道不需展示的市场列表，
--       同时硬编码排除 'AIA ALL Market' 聚合行。
-- 修改时间: 20241118  修改人: Fanxujia
-- =============================================================================
-- COMMAND ----------

WITH hidden_market AS (
    SELECT DISTINCT
        -- 将手工文件中的简写 data_source 标准化为系统内的完整名称
        CASE UPPER(data_source)
            WHEN 'CHPA'    THEN 'IQVIA-CHPA(Monthly)'
            WHEN '科室市场' THEN 'XH Data(Quarterly)'
            WHEN 'EC'      THEN 'EC(Monthly)'
            WHEN 'RETAIL'  THEN 'Retail(Quarterly)'
            WHEN 'CHC'     THEN 'CHC(Quarterly)'
            WHEN 'AIA'     THEN 'AIA(Monthly)'
            WHEN 'THC'     THEN 'THC(Quarterly)'
            WHEN 'COUNTY'  THEN 'IQVIA-COUNTY(Quarterly)'
            ELSE                 data_source
        END                          AS data_source,
        UPPER(hidden_market)         AS hidden_market
    FROM dwd.dwd_gnd_ims_hidden_market

    UNION ALL

    -- 固定排除 AIA 的全市场聚合行
    SELECT 'AIA(Monthly)' AS data_source, 'ALL MARKET' AS hidden_market
)

MERGE INTO dm.DM_TD_EXT_AIA_ORG AS t1
USING hidden_market                AS t2
   ON t1.DATA_SOURCE      = t2.data_source
  AND UPPER(t1.MARKET)    = t2.hidden_market   -- hidden_market 已在 CTE 中 UPPER 化，减少重复计算
WHEN MATCHED THEN DELETE;

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

-- WITH

-- -- ----------------------------------------------------------------------------
-- -- [基础配置] CVH 考核月份白名单
-- -- ----------------------------------------------------------------------------
-- cvh_ym AS (
--     SELECT key_value AS yyyymm
--     FROM   dm.dm_td_date_config
--     WHERE  key_code = 'pfmc_cvh'
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [输入数据] 事实表中所有有效的 机构×市场 组合（作为主驱动集合）
-- -- ----------------------------------------------------------------------------
-- all_audit_market AS (
--     SELECT DISTINCT
--         NVL(s.AUDIT_COD, 'ROC')       AS audit_cod,
--         NVL(m.market,   'ALL Market') AS market
--     FROM   dm.dm_ext_aia_sales             s
--     LEFT JOIN dm.dm_td_ext_aia_market_pack_mapping m
--            ON s.pack_cod = m.PACK_CODE
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [参照表] Pack → Market 映射
-- -- ----------------------------------------------------------------------------
-- pack_market AS (
--     SELECT DISTINCT
--         PACK_CODE AS pack_cod,
--         market
--     FROM dm.dm_td_ext_aia_market_pack_mapping
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [参照表] 城市 → 大区中心映射（AIA 渠道）
-- -- ----------------------------------------------------------------------------
-- external_geo AS (
--     SELECT DISTINCT
--         CONCAT(city_c, '市') AS city_c,
--         REGION_CENTER
--     FROM DM.DM_TD_EXTERNAL_GEO_TEMP
--     WHERE DATA_SOURCE = 'AIA(Monthly)'
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [内部组织] CVH 月份范围内的 org 层级数据
-- -- Vacant 岗位用 kcode 替代，便于前端展示
-- -- ----------------------------------------------------------------------------
-- org AS (
--     SELECT DISTINCT
--         o.yyyymm,
--         o.bu_category,
--         o.bu_code,
--         o.bu_name_en,
--         o.sub_bu_code,
--         o.sub_bu_name,
--         o.REGION_CODE,
--         o.region_name,
--         o.rc_code,
--         o.rc_name,
--         o.district_name                                                       AS team,
--         o.mr_trty_code,
--         o.nsd_kcode,
--         CASE WHEN o.nsd_name = 'Vacant' THEN o.nsd_kcode ELSE o.nsd_name END AS nsd_name,
--         o.rsd_kcode,
--         CASE WHEN o.rsd_name = 'Vacant' THEN o.rsd_kcode ELSE o.rsd_name END AS rsd_name,
--         o.rsm_kcode,
--         CASE WHEN o.rsm_name = 'Vacant' THEN o.rsm_kcode ELSE o.rsm_name END AS rsm_name,
--         o.dsm_kcode,
--         CASE WHEN o.dsm_name = 'Vacant' THEN o.dsm_kcode ELSE o.dsm_name END AS dsm_name,
--         o.mr_kcode,
--         CASE WHEN o.mr_name  = 'Vacant' THEN o.mr_kcode  ELSE o.mr_name  END AS mr_name
--     FROM  dm_td_org_temp o
--     INNER JOIN cvh_ym    c ON o.yyyymm = c.yyyymm
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [正常路径 1/3] CVH 月份范围内的 Territory 指示表
-- -- 排除 CUBE、KA；双考场景仅保留 key_hp=1 或非 Eagle 的 key_hp=2 记录
-- -- 修改: chenwu 20250904
-- -- ----------------------------------------------------------------------------
-- territory AS (
--     SELECT DISTINCT
--         t.yyyymm,
--         t.trty_code,
--         t.inst_code,
--         t.family_code
--     FROM   dm.dm_td_sd_territory_indication t
--     INNER JOIN cvh_ym c ON t.yyyymm = c.yyyymm
--     WHERE  t.bu NOT IN ('CUBE', 'KA')
--       AND  (
--                (t.key_hp = 2 AND t.bu <> 'Retail' AND t.trty_code <> 'Eagle')
--             OR  t.key_hp = 1
--            )
-- ),

-- -- ----------------------------------------------------------------------------
-- -- [正常路径 2/3] Territory → 机构 → 城市 → 市场 映射
-- -- family_code 经 product_wide → imscode_azcode → pack_market 三跳转换
-- -- ----------------------------------------------------------------------------
-- inst_pack_base AS (
--     SELECT DISTINCT
--         t.yyyymm,
--         t.trty_code,
--         t.inst_code,
--         i.city_name,
--         pm.market,
--         CASE i.area_code
--             WHEN 'SOUTH'   THEN 'South'
--             WHEN 'WEST'    THEN 'West'
--             WHEN 'CENTRAL' THEN 'Central'
--             WHEN 'NORTH'   THEN 'North'
--             WHEN 'EAST'    THEN 'East'
--         END AS region_center
--     FROM   territory                   t
--     LEFT JOIN dwd.dwd_td_institution   i  ON t.inst_code    = i.inst_code
--     LEFT JOIN cdw_dwd_dim_product_wide p  ON t.family_code  = p.prd_family_cd
--     LEFT JOIN dwd.dwd_td_imscode_azcode az ON p.prd_brand_cd = az.brandcode
--     LEFT JOIN pack_market              pm ON az.ims_pack_cod = pm.pack_cod
-- ),

-- -- [正常路径 3/3] 可定架构（Rosuvastatin Market）复制到立普妥（Atorvastatin Market）
-- -- 修改: Chenwu 20251207
-- inst_pack AS (
--     SELECT * FROM inst_pack_base
--     UNION ALL
--     SELECT yyyymm, trty_code, inst_code, city_name,
--            'Atorvastatin Market' AS market,
--            region_center
--     FROM   inst_pack_base
--     WHERE  market = 'Rosuvastatin Market'
-- ),

-- -- ============================================================================
-- -- [Eagle 回退路径] 部分机构未能通过正常 territory 路径挂上架构，
-- --                 改用 城市+品牌 关系匹配 Eagle territory code
-- -- 修改: Chenwu 20250220
-- -- ============================================================================

-- -- Eagle: city × family → territory code（多个时取 PROJECT_CD 最大者）
-- eagle_trty AS (
--     SELECT SP_TRTY_CD, CITY_CD, FAMILY_CD
--     FROM (
--         SELECT
--             SP_TRTY_CD, CITY_CD, FAMILY_CD,
--             ROW_NUMBER() OVER (PARTITION BY CITY_CD, FAMILY_CD ORDER BY PROJECT_CD DESC) AS rn
--         FROM (
--             SELECT eg.SP_TRTY_CD, eg.CITY_CD, eg.FAMILY_CD, eg.PROJECT_CD
--             FROM   dws.dws_td_eg_cityterritory        eg
--             INNER JOIN cvh_ym                          c  ON eg.YM = c.yyyymm
--             -- 仅保留非 Eagle BU 已覆盖的 territory（Anti-Join，性能优于 NOT IN 子查询）
--             LEFT  JOIN (
--                 SELECT DISTINCT trty_code
--                 FROM dm.dm_td_sd_territory_indication
--                 WHERE bu = 'Eagle'
--             )                                          ex ON eg.SP_TRTY_CD = ex.trty_code
--             -- 仅医院类项目
--             INNER JOIN (
--                 SELECT DISTINCT project_code
--                 FROM DWS.dws_td_eg_project_instype
--                 WHERE ins_type = '医院'
--             )                                          pi ON eg.PROJECT_CD = pi.project_code
--             WHERE  ex.trty_code IS NULL                   -- Anti-Join 条件
--               AND  NVL(eg.SALES_RATE, 0) <> 0             -- 排除零销售比例（原逻辑：cast <> '0.000000'）
--             GROUP BY eg.SP_TRTY_CD, eg.CITY_CD, eg.FAMILY_CD, eg.PROJECT_CD
--         ) base
--     ) deduped
--     WHERE rn = 1
-- ),

-- -- Eagle territory → 市场 映射（family → brand → pack → market，city code → city name）
-- eagle_mapping AS (
--     SELECT
--         et.SP_TRTY_CD,
--         g.city_name,
--         pm.market
--     FROM   eagle_trty                   et
--     LEFT JOIN cdw_dwd_dim_product_wide  p  ON et.FAMILY_CD    = p.prd_family_cd
--     LEFT JOIN dwd.dwd_td_imscode_azcode az ON p.prd_brand_cd  = az.brandcode
--     LEFT JOIN dm.dm_td_geography        g  ON et.CITY_CD      = g.city_code
--     INNER JOIN pack_market              pm ON az.ims_pack_cod  = pm.pack_cod
--     GROUP BY et.SP_TRTY_CD, g.city_name, pm.market
-- ),

-- -- Audit 机构 → 城市 映射
-- audit_geo AS (
--     SELECT   AUDIT_COD, MAX(CITY_C) AS city_c
--     FROM     DM.DM_TD_EXTERNAL_GEO
--     WHERE    DATA_SOURCE = 'AIA(Monthly)'
--     GROUP BY AUDIT_COD
-- ),

-- -- 汇总：对 all_audit_market 中无法通过 inst_pack 匹配的记录，
-- -- 尝试用 Eagle 城市+市场 回退挂上 territory code
-- eagle_trty_with_city AS (
--     SELECT
--         am.AUDIT_COD,
--         am.market,
--         ag.city_c,
--         em.SP_TRTY_CD
--     FROM   all_audit_market am
--     LEFT JOIN audit_geo      ag ON am.AUDIT_COD  = ag.AUDIT_COD
--     LEFT JOIN eagle_mapping  em ON em.city_name  = ag.city_c
--                                 AND em.market     = am.market
--     WHERE  em.SP_TRTY_CD IS NOT NULL   -- 仅保留能匹配到 Eagle territory 的行
--     GROUP BY am.AUDIT_COD, am.market, ag.city_c, em.SP_TRTY_CD
-- )

-- -- ----------------------------------------------------------------------------
-- -- 主写入：覆盖写目标表
-- -- 优先级: t2（正常路径 org）> t6（Eagle 回退 org）> 硬编码默认值
-- -- ----------------------------------------------------------------------------

-- -- SELECT DISTINCT
-- --     COALESCE(t2.REGION_CODE,  t6.REGION_CODE,  'ROC') AS REGION_CODE,
-- --     COALESCE(t2.region_name,  t6.region_name,  'ROC') AS region_name_en,
-- --     COALESCE(t2.rc_code,      t6.rc_code,      'ROC') AS rc_code,
-- --     COALESCE(t2.rc_name,      t6.rc_name,      'ROC') AS rc_name_en,
-- --     COALESCE(t1.region_center, t4.REGION_CENTER, t7.REGION_CENTER, '') AS RegionCenter,
-- --     t0.audit_cod,
-- --     t0.market,
-- --     COALESCE(t2.bu_category,  t6.bu_category,  '')        AS bu_category,
-- --     COALESCE(t2.bu_name_en,   t6.bu_name_en,   '')        AS bu_name_en,
-- --     COALESCE(t2.sub_bu_name,  t6.sub_bu_name,  '')        AS sub_bu_name,
-- --     COALESCE(t2.sub_bu_code,  t6.sub_bu_code,  '')        AS sub_bu_code_auth,
-- --     CONCAT(COALESCE(t2.bu_code, t6.bu_code, ''), 'AIA(Monthly)') AS bu_code_auth,
-- --     'AIA(Monthly)'                                        AS DATA_SOURCE,
-- --     1                                                     AS REGION_RATIO,
-- --     COALESCE(t2.rsm_name,     t6.rsm_name,     'Vacant') AS RSM_Name,
-- --     COALESCE(t2.rsd_name,     t6.rsd_name,     'Vacant') AS RC_Name,
-- --     COALESCE(t2.team,         t6.team,         'ROC')    AS TEAM,
-- --     COALESCE(t2.mr_trty_code, t6.mr_trty_code, 'Vacant') AS MR_TRTY_CODE,
-- --     COALESCE(t2.nsd_kcode,    t6.nsd_kcode,    'Vacant') AS NSD_KCODE,
-- --     COALESCE(t2.nsd_name,     t6.nsd_name,     'Vacant') AS NSD_NAME,
-- --     COALESCE(t2.rsd_kcode,    t6.rsd_kcode,    'Vacant') AS RSD_KCODE,
-- --     COALESCE(t2.rsd_name,     t6.rsd_name,     'Vacant') AS RSD_NAME,
-- --     COALESCE(t2.rsm_kcode,    t6.rsm_kcode,    'Vacant') AS RSM_KCODE,
-- --     COALESCE(t2.dsm_kcode,    t6.dsm_kcode,    'Vacant') AS DSM_KCODE,
-- --     COALESCE(t2.dsm_name,     t6.dsm_name,     'Vacant') AS DSM_NAME,
-- --     COALESCE(t2.mr_kcode,     t6.mr_kcode,     'Vacant') AS MR_KCODE,
-- --     COALESCE(t2.mr_name,      t6.mr_name,      'Vacant') AS MR_NAME
-- -- FROM all_audit_market t0
-- -- -- ── 正常路径 ──────────────────────────────────────────────────────────────
-- -- LEFT JOIN inst_pack      t1 ON  t0.audit_cod = t1.inst_code
-- --                             AND t0.market    = t1.market
-- -- LEFT JOIN org            t2 ON  t1.trty_code = t2.mr_trty_code
-- --                             AND t1.yyyymm    = t2.yyyymm
-- -- LEFT JOIN external_geo   t4 ON  t1.city_name = t4.city_c
-- -- -- ── Eagle 回退路径（仅当正常路径未能匹配机构时） ──────────────────────────
-- -- LEFT JOIN eagle_trty_with_city t5 ON  t0.audit_cod  = t5.AUDIT_COD
-- --                                   AND t0.market     = t5.market
-- --                                   AND t1.inst_code IS NULL   -- 正常路径未命中
-- -- LEFT JOIN org            t6 ON  t5.SP_TRTY_CD = t6.mr_trty_code
-- -- LEFT JOIN external_geo   t7 ON  t5.city_c     = t7.city_c
-- select * from inst_pack t1
-- LEFT JOIN org            t2 ON  t1.trty_code = t2.mr_trty_code
--                             AND t1.yyyymm    = t2.yyyymm
-- where t1.inst_code = 'ZJTZ006H'

-- and t1.market = 'Oral lipid-lowering Market(Excl Potent Statin)'
