首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何添加按正确顺序显示的日期(月份),现在它在递归CTE SQL中向后显示

如何添加按正确顺序显示的日期(月份),现在它在递归CTE SQL中向后显示
EN

Stack Overflow用户
提问于 2020-08-31 21:38:15
回答 2查看 22关注 0票数 0
代码语言:javascript
运行
复制
with recursive cte (id, qty) (
    select id, qty from mytable
    union all
    select id, qty - 1 from cte where qty > 1
)
select id from cte order by id

问题:

如何添加按正确顺序显示的日期(月份),现在它在递归CTE中向后显示?

代码语言:javascript
运行
复制
with recursive cte (id, qty, Forecast_date) 
( 
select id, qty, StartDate from mytable 
union all 
select id, qty - 1, eomonth(dateadd(month, 1,Forecast_date)) from cte where qty > 1 ) 

select id,Forecast_date from cte order by id

输出:

代码语言:javascript
运行
复制
9/30/2023   0
8/31/2023   1
7/31/2023   2
6/30/2023   3
5/31/2023   4
4/30/2023   5
3/31/2023   6
2/28/2023   7
1/31/2023   8
12/31/2022  9
11/30/2022  10
10/31/2022  11
9/30/2022   12
8/31/2022   13
7/31/2022   14
6/30/2022   15
5/31/2022   16
...

预期增量启动5/31/2022年,而不是2023-09-30,这应该是最后一次记录

重点是:

代码语言:javascript
运行
复制
Id  Forecast_date  qty
1   5/31/2022      0
2   6/30/2022      1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-31 21:52:29

减去种子选择中的月数:

代码语言:javascript
运行
复制
with recursive cte (id, qty, Forecast_date) 
(
select id, qty, eomonth(dateadd(month, -qty,StartDate)) 
from mytable 
union all 
select id, qty - 1, eomonth(dateadd(month, 1,Forecast_date)) 
from cte 
where qty >= 1 
) 

select * 
from cte 
order by id, qty

或者添加另一列,以qty 0开头,然后向上计数,而不是倒计时:

代码语言:javascript
运行
复制
with recursive cte (id, qty, Forecast_date, stopat)
( 
select id, 0, StartDate, qty
from mytable 
union all 
select id, qty + 1, eomonth(dateadd(month, 1,Forecast_date)), stopat
from cte 
where qty < stopat 
) 

select id, qty, Forecast_date
from cte 
order by id, qty
票数 1
EN

Stack Overflow用户

发布于 2020-08-31 21:45:51

从生成递增序列开始,然后在外部查询中进行计算可能更简单:

代码语言:javascript
运行
复制
with recursive cte (id, qty, forecast_date, lvl) (
    select id, qty, datefromparts(year(forecast_date), month(forecast_date), 1), 0 lvl from mytable
    union all
    select id, qty, forecast_date, lvl + 1 from cte where lvl < qty
)
select 
    id,
    qty - lvl as dty,
    eomonth(dateadd(month, -lvl, forecast_date)) new_forecast_date
from cte
order by id, new_forecast_date

月底的计算很棘手:您不能通过添加月份从月底跳转到另一个月,因为并非所有月份都有相同的天数。因此,查询使用开始月份的开始进行计算,然后使用eomonth()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63678528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档