sql - 在日期范围之间递归输入月份年份名称
问题描述
我正在尝试根据时间范围将下面的以下列插入#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|
________________________________________________________________________________
解决方案
递归 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。
推荐阅读
- firebase - 是否可以使用 React Native Firebase 中的下载 URI 获取 firebase 存储中文件的引用?
- reactjs - ReactJS 中的 Cookie.js 在渲染/路由到配置文件页面时将角色值设置为未定义
- python - 我想从 python 3.8 的列表中删除特定元素及其重复项
- javascript - 为什么我的谷歌表格函数返回 TypeError: given_list is not iterable?或者:如何将数组输入到谷歌表格函数中?
- swift - React Native Firebase - 使用 IOS 时在数字元素数组上使用“array-contains-any”失败
- python - 使用句子转换器/pytorch 对大量文档进行编码的正确方法是什么?
- python - 使用 groupby 和 cumcount (pandas) 计算每列的连续字符串
- javascript - 为什么我们不能使用 DOM getElementsByClassName 选择的变量的 addEventListener?
- angular - WebStorm 2020.3 中的 Angular 模板在最近更新后显示未解析的管道和变量
- javascript - 用 array.map 反应渲染表元素