WITH MonthTally (M) AS ( select M = 1 union all select M + 1 from MonthTally where M < 12 ) , YearTally(Y) as ( --建立年份範圍 select Y = 2019 union all select Y + 1 from YearTally where Y < 2020 ) SELECT CAST(Y as NVARCHAR) + RIGHT(REPLICATE('0', 2) + CAST(M as NVARCHAR), 2) + '01' startdate --轉換日期格式 , CONVERT(VARCHAR, --取得該年該月最後一日 EOMONTH ( CAST(Y as NVARCHAR) + RIGHT(REPLICATE('0', 2) + CAST(M as NVARCHAR), 2) + '01' ) ,112) enddate FROM MonthTally CROSS JOIN YearTally
select n from generate_series( '2020-01-01'::timestamp , '2020-12-31'::timestamp , interval'1 day' ) n where n in ( date_trunc('month', n) + interval'1 month' - interval'1 day' , to_char(n , 'YYYY-MM-01')::date )