我有以下SQL代碼,如果'COV_PRD_STRT_DT'和'COV_PRD_END_DT'是不同的月份,我需要將行分成兩行。如何在SQL中編寫拆分語句,如果開始和結束日期的月份不同,則會將記錄劃分爲2條記錄?
WITH CTE AS
(SELECT COV_PRD_STRT_DT,TO_DATE,COV_PRD_END_DT as MO_END_DT,
case when dateadd (DAY,-DAY(DATEADD(MONTH,1, BF.COV_PRD_STRT_DT)),
DATEADD(MONTH,1, d.from_date))
< To_date THEN DATEADD(DAY,-DAY(DATEADD(MONTH,1, BF.COV_PRD_END_DT)),
DATEADD(MONTH,1, BF.COV_PRD_END_DT))
ELSE To_Date END as MO_END_DT
FROM BILLING_FACT
UNION ALL
SELECT COV_PRD_STRT_DT,To_date,DATEADD(DAY,1,BF.COV_PRD_END_DT) as MO_END_DT, < TO_DATE
THEN DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(DAY,1,BF.COV_PRD_END_DT)))
ELSE To_Date END as MO_END_DT
FROM CTE WHERE COV_PRD_END_DT < To_Date
)
select * from CTE order by COV_PRD_STRT_DT,COV_PRD_END_DT
感謝
可以顯示一些示例數據和預期結果嗎? –
@FerdinandGaspar - 嗨,不幸的是,我不能提供樣本數據,因爲它的PHI – user8611702
可以是一些組成樣本,但具有相同的數據類型 –