We can use CTE (common table expression) to get a list of month.
;WITH DateYear AS
(
SELECT 0 AS num
UNION ALL
SELECT num + 1 FROM DateYear
WHERE num < 11
)
SELECT CONVERT(DATE,DATEADD(MONTH,(num-13),convert(datetime, '20140401', 110))) AS MyMonth from DateYear
If you have multipel CTE, use comma to seperate them.
;WITH SomeClause1 AS
(
SELECT ....
)
, SomeClause2 AS
(
SELECT ....
)
Reference:
本文介绍了一种使用SQL中的CTE(通用表表达式)来生成一系列月份的方法。通过递归地创建数字序列并利用DATEADD函数,可以有效地生成指定范围内的所有月份。此外,还介绍了如何在同一查询中使用多个CTE。
2万+

被折叠的 条评论
为什么被折叠?



