[英]How to get a month prior date from a given date in SQL?
I am trying to get a month dates from the @EndDate
including provided date ( @EndDate
) in SQ Server 2008.我试图从
@EndDate
获取一个月的日期,包括 SQ Server 2008 中提供的日期( @EndDate
)。
@NoOfMonths
is a variable which decides how much previous months dates we need. @NoOfMonths
是一个变量,它决定了我们需要多少前几个月的日期。 eg例如
@EndDate = 2020-07-28
@NoOfMonths = 6
Expected result would be:预期结果是:
2020-07-28
2020-06-28
2020-05-28
2020-04-28
2020-03-28
2020-02-28
I am trying using below recursive CTE query, however the results are not expected, I am getting month end dates.我正在尝试使用以下递归 CTE 查询,但是结果出乎意料,我得到了月末日期。
@EndDate: 2020-07-28
@NoOfMonths = 6
Result:结果:
2020-07-31
2020-06-30
2020-05-31
2020-04-30
2020-03-31
2020-02-29
Code:代码:
DECLARE @EndDate DATE = CAST('2020 - 07 - 28' AS DATE);
DECLARE @NoOfMonths INT = 6;
WITH CTE_previousMonths AS
(
SELECT
CAST(DATEADD(ss, -1, DATEADD(mm, DATEDIFF(m, -1, @EndDate), 0)) AS DATE) AS MonthPriorDate,
1 AS months
UNION ALL
SELECT
CAST(DATEADD(ss, -1, DATEADD(mm, DATEDIFF(m, 0, MonthPriorDate), 0)) AS DATE) AS MonthPriorDate,
months + 1 AS months
FROM
CTE_previousMonths
WHERE
months < @NoOfMonths
)
SELECT CTE_previousMonths.MonthPriorDate
FROM CTE_previousMonths;
Thanks!谢谢!
I think this should do what you want:我认为这应该做你想做的:
with n as (
select 1 as n
union all
select n + 1
from n
where n < @NoOfMonths
)
select dateadd(month, 1 - n, @enddate)
from n;
Using Eomonth function:使用 Eomonth 函数:
WITH cte1 as
(
select EOMONTH('2020-07-28') as last_date, DATEADD(MONTH, -5, EOMONTH('2020-07-28')) AS END_DATE--Number of months - 1
union all
select DATEADD(MONTH, -1, last_date), END_DATE FROM CTE1 WHERE LAST_DATE > END_DATE
)
SELECT last_date FROM cte1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.