-- Databricks notebook source
-- 源表：DWS.DWS_IMS_TD_DATE
-- 目标表：DM.DM_IMS_TD_CALENDAR,DM.DM_IMS_S_DATE

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

--DM 逻辑 
--DATE
INSERT OVERWRITE TABLE DM.DM_IMS_TD_CALENDAR
--当前年销量日期日历表缺少的用去年补全
SELECT 
  CAST(YM+100 AS INT) AS YYYYMM,
  CAST(YEAR+1 AS INT) AS YEAR,
  MONTH,
  QUARTER,
  CONCAT(CAST(LEFT(YQ,4) AS INT)+1,QUARTER) AS YQ ,
  CAST(CONCAT(CAST(YEAR AS INT)+1,'-',MONTH,'-01') AS DATE) AS DAY_DATE,
  CASE WHEN YM+100= (SELECT MAX(YM) FROM TMP.TMP_IMS_TF_FACT_SALES) THEN 'R' ELSE DATE_FLAG END, 
  CONCAT(CAST(LEFT(HALF_YEAR,4) AS INT)+1,RIGHT(HALF_YEAR,2)) AS HALF_YEAR,
  FROM_UTC_TIMESTAMP(CURRENT_TIMESTAMP(),'UTC+8') ETL_INSERT_DT,
  FROM_UTC_TIMESTAMP(CURRENT_TIMESTAMP(),'UTC+8') ETL_UPDATE_DT
FROM DWS.DWS_IMS_TD_DATE
WHERE YEAR+1=(SELECT MAX(YEAR) FROM DWS.DWS_IMS_TD_DATE)

--前四年的日历表
UNION ALL 

SELECT 
  CAST(YM AS INT) AS YYYYMM,
  CAST(YEAR AS INT),
  MONTH,
  QUARTER,
  YQ,
  CAST(CONCAT(YEAR,'-',MONTH,'-01') AS DATE) AS DAY_DATE,
  DATE_FLAG,
  HALF_YEAR,
  FROM_UTC_TIMESTAMP(CURRENT_TIMESTAMP(),'UTC+8') ETL_INSERT_DT,
  FROM_UTC_TIMESTAMP(CURRENT_TIMESTAMP(),'UTC+8') ETL_UPDATE_DT
FROM DWS.DWS_IMS_TD_DATE
WHERE YEAR<(SELECT MAX(YEAR) FROM DWS.DWS_IMS_TD_DATE)
  AND YEAR+9>(SELECT MAX(YEAR) FROM DWS.DWS_IMS_TD_DATE)


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

INSERT OVERWRITE TABLE DM.DM_IMS_S_DATE  
SELECT 
  YYYYMM,
  YEAR,
  MONTH,
  QUARTER,
  YQ,
  DAY_DATE,
  DATE_FLAG,
  HALF_YEAR,
  ETL_INSERT_DT,
  ETL_UPDATE_DT
FROM DM.DM_IMS_TD_CALENDAR