-- Databricks notebook source
--对折算规则文件中的Pack，Mole code 补0
--时间条件为空的，赋默认值
--地理维度表增加KCT和ROC
UPDATE dwd.dwd_gnd_ims_tblBrandRatio 
SET 
PACK_COD =   if( CAST(PACK_COD AS string) REGEXP '^[0-9]',right(concat('000000000000',CAST(PACK_COD AS string)),12),CAST(PACK_COD AS string)),
CMPS_COD = RIGHT(concat('000000',CAST(CMPS_COD AS string)),6),
StartTime = CASE WHEN StartTime IS NULL OR UPPER(StartTime)= 'ALL' THEN '190001' ELSE StartTime END, 
EndTime = CASE WHEN EndTime IS NULL OR UPPER(EndTime)= 'ALL' THEN '209901' ELSE EndTime END
;


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

-- 20260119 这个补0操作，可以放最前面，或者专门找个地方放。
----确保Market和KeyCompetitor配置表中，Pack_Code，Product_Code，Molecule_Code 三个字段都已经补0


UPDATE dwd.dwd_gnd_tblmarket_bymonth 
--20250428 chenwu iqivacode扩到12位,brandcode 扩到9位
SET Pack_Code = if( Pack_Code REGEXP '^[0-9]',right(concat('000000000000',Pack_Code),12),Pack_Code) 
,Product_Code = RIGHT(concat('000000000',Product_Code),9) --RIGHT(concat('00000',Product_Code),5)
,Molecule_Code = RIGHT(concat('000000',Molecule_Code),6)
;

INSERT OVERWRITE TABLE dwd.dwd_gnd_ims_tblmarket
(
  market_no,
  market,
  bu,
  atc1_code,
  atc2_code,
  atc3_code,
  atc4_code,
  nfc1_code,
  nfc2_code,
  nfc3_code,
  pack_code,
  pack_desc,
  strength,
  product_code,
  product_desc,
  molecule_code,
  molecule_desc,
  not_in_flag,
  extend_market,
  extend_market_ratio,
  corporation_code,
  corporation_desc,
  manufacturer_code,
  manufacturer_desc
)
SELECT DISTINCT
  market_no,
  market,
  bu,
  atc1_code,
  atc2_code,
  atc3_code,
  atc4_code,
  nfc1_code,
  nfc2_code,
  nfc3_code,
  pack_code,
  pack_desc,
  strength,
  product_code,
  product_desc,
  molecule_code,
  molecule_desc,
  not_in_flag,
  extend_market,
  extend_market_ratio,
  corporation_code,
  corporation_desc,
  manufacturer_code,
  manufacturer_desc
FROM dwd.dwd_gnd_tblmarket_bymonth;

UPDATE dwd.dwd_gnd_ims_tblkeycompetitor 
SET Pack_Code = if( Pack_Code REGEXP '^[0-9]',right(concat('000000000000',Pack_Code),12),Pack_Code)
,Product_Code = RIGHT(concat('000000000',Product_Code),9) --RIGHT(concat('00000',Product_Code),5)
,Molecule_Code = RIGHT(concat('000000',Molecule_Code),6)
;
UPDATE dwd.dwd_gnd_ims_tblbrandtype 
SET PACK_COD = if( PACK_COD REGEXP '^[0-9]',right(concat('000000000000',PACK_COD),12),PACK_COD) --RIGHT(concat('0000000',PACK_COD),7)
;