首页 > 解决方案 > 在日期范围之间递归输入月份年份名称

问题描述

我正在尝试根据时间范围将下面的以下列插入#table。

例如,如果查询在 2020 年 8 月运行,我需要它插入从2020 年 1 月到 2020 年 7月的月份名称

Report_Date_Name|   Report_Date_Month|  DateYrmo|   DateYear|   DateMonth|
January     2020|             January|    202001|       2020|           1|
February    2020|            February|    202002|       2020|           2|
March       2020|               March|    202003|       2020|           3|
April       2020|               April|    202004|       2020|           4|
May         2020|                 May|    202005|       2020|           5|
June        2020|                June|    202006|       2020|           6|
July        2020|                July|    202007|       2020|           7|


________________________________________________________________________________

标签: sqlsql-serverdatetsql

解决方案


递归 CTE 似乎是一种简单的方法:

with dates as (
      select datefromparts(year(getdate()), 1, 1) as dte
      union all
      select dateadd(month, 1, dte)
      from dates
      where dte < getdate()
     )
select concat(convert(char(12), datename(month, dte)), year(dte)) as report_date_name,
       datename(month, dte) as report_date_month,
       year(dte) * 100 + month(dte) as year_month,
       year(dte) as year
from dates;

目前尚不清楚最后一列是字符串还是数字。如果是字符串,只需将它们转换为您想要的类型。

是一个 db<>fiddle。


推荐阅读