使用递归 CTE 获取给定月份和月份的逗号分隔月份

发布于 2024-12-09 11:05:14 字数 298 浏览 0 评论 0原文

我们要求提供 2 个月和 2 年作为输入。结果应提供以逗号分隔的月年和从月年到月年之间的所有月份。

假设我们有

From Month is 'Jan' 
From Year is 2011
To Month is 'Apr'
To Year is 2011

想要的输出,

Jan'11,Feb'11,Mar'11,Apr'11

这可以使用递归 CTE 来实现吗?我们需要使用递归 CTE 来实现这一点。有人可以帮我解决这个问题吗?

We have requirement where 2 months and 2 years are provided as input. And the result should provide a comma separated month-year all the months between the from month-year and to month-year.

Say, we have

From Month is 'Jan' 
From Year is 2011
To Month is 'Apr'
To Year is 2011

desired output

Jan'11,Feb'11,Mar'11,Apr'11

Can this be achieved using recursive CTE? We need to achieve this using recursive CTE. Could somebody help me on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹微笑 2024-12-16 11:05:14

试试这个代码:

--declaration of variables
declare @frommonth char(3) = 'jan',@fromyear char(4) = 2011,
        @tomonth char(3) = 'APR', @toyear char(4) = 2011
         
declare @output varchar(max)
declare @f int, @t int 

select --setting from and to month as months after 1900-01-01
@f = datediff(month, 0, cast('1' +@frommonth+@fromyear as datetime)),
@t = datediff(month, 0, cast('1' +@tomonth+@toyear as datetime))

-- recusive loop
;with cte as
(
select @f m
union all
select m + 1 from cte
where m < @t
)
select @output = coalesce(@output +',', '') +stuff(convert(varchar(11),dateadd(mm, m, 0), 109), 4, 6, '''') FROM CTE

select @output

结果:

Jan'11,Feb'11,Mar'11,Apr'11

在这里测试:

https://data.stackexchange .com/stackoverflow/q/114801/变量声明

Try this code:

--declaration of variables
declare @frommonth char(3) = 'jan',@fromyear char(4) = 2011,
        @tomonth char(3) = 'APR', @toyear char(4) = 2011
         
declare @output varchar(max)
declare @f int, @t int 

select --setting from and to month as months after 1900-01-01
@f = datediff(month, 0, cast('1' +@frommonth+@fromyear as datetime)),
@t = datediff(month, 0, cast('1' +@tomonth+@toyear as datetime))

-- recusive loop
;with cte as
(
select @f m
union all
select m + 1 from cte
where m < @t
)
select @output = coalesce(@output +',', '') +stuff(convert(varchar(11),dateadd(mm, m, 0), 109), 4, 6, '''') FROM CTE

select @output

Result:

Jan'11,Feb'11,Mar'11,Apr'11

Test here:

https://data.stackexchange.com/stackoverflow/q/114801/declaration-of-variables

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文