-- Databricks notebook source
--笛卡尔积生成PKAU维度表
insert overwrite table tmp.tmp_ims_county_pack_audit 
SELECT 
  PACK.Pack_ID, 
  if( Pack_Code REGEXP '^[0-9]',right(concat('000000000000',Pack_Code),12),Pack_Code) as PACK_CODE,--RIGHT(concat('0000000',Pack_Code),7)
  AUDI.Audit_ID,
  AUDI.Audit_Name AS AUDIT_COD,
  concat(REPLACE(AUDI.Audit_Name,' ','') , '_', if( Pack_Code REGEXP '^[0-9]',right(concat('000000000000',Pack_Code),12),Pack_Code))as PKAU_INDEX,
  from_utc_timestamp(current_timestamp,'UTC+8')     as etl_insert_dt,
  from_utc_timestamp(current_timestamp,'UTC+8')     as etl_update_dt
FROM dwd.dwd_gnd_county_dim_pack PACK
CROSS JOIN (
  SELECT 
    Audit_ID,
    Audit_Type,
    Audit_Name 
  FROM dwd.dwd_gnd_county_dim_audit
) AUDI

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

---------------------------------------------事实表添加lastyear的KPI字段---------------------------------------------
insert overwrite table tmp.tmp_ims_county_fact_sales_sum 
select 
distinct
t1.qtr
,left(t1.qtr,4)*100+right(t1.qtr,1)*3 as yyyymm
,t2.pack_code as pack_cod
,t2.audit_cod as region_cod
,sum(SalesValue_LC  ) as SalesValue_LC
,sum(SalesValue_LC_LY) as SalesValue_LC_LY
,sum(Counting_Unit  ) as Counting_Unit
,sum(Counting_Unit_LY) as Counting_Unit_LY
,sum(Sales_Unit  ) as Sales_Unit
,sum(Sales_Unit_LY) as Sales_Unit_LY 
,from_utc_timestamp(current_timestamp,'UTC+8') as etl_insert_dt
,from_utc_timestamp(current_timestamp,'UTC+8') as etl_update_dt
from(
  select DISTINCT left(concat(year,'Q',month/3),6) as qtr,pack_id,audit_id,
  nvl(SalesValue_LC,0) AS SalesValue_LC,
  0 AS SalesValue_LC_LY,
  nvl(Counting_Unit,0) AS Counting_Unit,
  0 AS Counting_Unit_LY,
  nvl(Sales_Unit,0) AS Sales_Unit,
  0 AS Sales_Unit_LY
  from dwd.dwd_gnd_county_fact_sales
  union all
  select DISTINCT left(concat(left(year,4),'Q',month/3),6) as qtr,pack_id,audit_id,
  0 AS SalesValue_LC,
  nvl(SalesValue_LC,0) AS SalesValue_LC_LY,
  0 AS Counting_Unit,
  nvl(Counting_Unit,0) AS Counting_Unit_LY,
  0 AS Sales_Unit,
  nvl(Sales_Unit,0) AS Sales_Unit_LY
  from (select DISTINCT year+1 as year,month,SalesValue_LC,Counting_Unit,Sales_Unit,pack_id,audit_id from dwd.dwd_gnd_county_fact_sales) fact_ly
  where year*100+month in (select distinct year*100+month from dwd.dwd_gnd_county_fact_sales)
)t1
left join tmp.tmp_ims_county_pack_audit t2 on t1.pack_id=t2.pack_id and t1.audit_id=t2.audit_id
group by t1.qtr,t2.pack_code,t2.audit_cod
