-- Databricks notebook source
insert overwrite table dws.dws_tf_external_retail_dtp_special 
with dim_geo as (
  SELECT 
    AUDIT_COD
    ,REGION_TYPE
    ,PROVINCE_C
  FROM DM.DM_TD_EXTERNAL_GEO 
  WHERE DATA_SOURCE = 'DTP(Quarterly)'
  GROUP BY 1,2,3
)
,all_data (--所有DTP BRAND 中的数据聚合
  select 
    market
    ,province_city
    ,yyyymm
    ,sum(sales_value)  as sales_value
    ,sum(sales_volume)  as sales_volume
    ,sum(pdot_counting_unit) as pdot_counting_unit
  from dwd.dwd_gnd_ext_dtp_zk_brand --数据来源表
  where type = '品类' 
  and market = 'EGFR TKI' 
  and zk_brand_category ='EGFR TKI Market'
  and ranked_by = 'value'
  group by 1,2,3
)
,not_quanguo_data as (--计算非全国部分
  select 
    market
    ,yyyymm
    ,sum(sales_value)  as sales_value
    ,sum(sales_volume)  as sales_volume
    ,sum(pdot_counting_unit) as pdot_counting_unit
  from all_data
  where province_city <> '全国'
  group by 1,2
)
,roc_data as (--计算 roc部分的值 = 全国- 非全国合计
  select 
    a.market
    ,'ROC' as province_city
    ,a.yyyymm
    ,a.sales_value-b.sales_value  as sales_value
    ,a.sales_volume - b.sales_volume  as sales_volume
    ,a.pdot_counting_unit - b.pdot_counting_unit  as pdot_counting_unit
  from all_data a
  left join not_quanguo_data b on a.market = b.market and a.yyyymm = b.yyyymm
  where a.province_city = '全国'
)
,all_data_with_roc as (--合并全部数据
  select 
    market
    ,province_city
    ,yyyymm
    ,sales_value
    ,sales_volume
    ,pdot_counting_unit
  from all_data where province_city <> '全国'
  union all
  select 
    market
    ,province_city
    ,yyyymm
    ,sales_value
    ,sales_volume
    ,pdot_counting_unit
  from roc_data 
)

select 
  a.market
  ,a.province_city
  ,concat(b.AUDIT_COD, 'DTP(Quarterly)', b.REGION_TYPE ) as audit_key --pbi dim_rc 关联键
  ,concat(b.AUDIT_COD, 'DTP(Quarterly)' ) audit_source --pbi dim_geo 关联键
  ,concat(left(a.yyyymm,4),'-',right(a.yyyymm,2),'-01') date_key --pbi dim_date 关联键
  ,a.yyyymm
  ,a.sales_value
  ,a.sales_volume
  ,a.pdot_counting_unit
from all_data_with_roc a 
left join dim_geo b on a.province_city = b.PROVINCE_C