Date split-up based on Fiscal Year

后端 未结 3 1981
南方客
南方客 2021-01-03 07:50

Given a From Date, To Date and a Fiscal Year system, I want to get all the split-up duration within the given From & To Date based on the Fisc

3条回答
  •  长情又很酷
    2021-01-03 08:26

    CREATE TABLE your_table (start_date date, end_date date); 
    INSERT INTO your_table VALUES (CONVERT (date, GETDATE()),CONVERT (date, DATEADD(year, -1, GETDATE())) ); 
    
    WITH mycte AS
     (
     SELECT 1 as id
     UNION ALL
     SELECT id + 1
     FROM mycte
     WHERE id + 1 < = 12
     ),
     cte_distribution as
     (
     SELECT *, 
     DATEPART (month,DATEADD(month, mycte.id - 1, your_table.start_date)) as month_number ,
     DATEPART (YEAR,DATEADD(month, mycte.id - 1, your_table.start_date)) as  cal_year,
     12000/12 as cash
     FROM your_table
     CROSS JOIN mycte
     )
     select 
     *,
     (CASE WHEN month_number between 1 and 3 THEN '1st quarter' WHEN month_number between 4 and 6 THEN '2nd quarter'  WHEN month_number between 7 and 9 THEN '3rd quarter' WHEN month_number between 9 and 12 THEN '4th quarter' END) as Quarter,
     CASE WHEN month_number between 1 and 6 THEN  CAST(CAST((cal_year - 1) as CHAR(4)) + '-' + CAST(cal_year as CHAR(4)) AS CHAR(9))  WHEN  month_number between 6 and 12 THEN CAST(CAST((cal_year) as CHAR(4)) + '-' + CAST((cal_year + 1) as CHAR(4)) AS CHAR(9))  ELSE NULL END as fin_year
     from cte_distribution;
    

提交回复
热议问题