SQL列表在两个日期之间重复发生日期,结束日期为下一个开始日期

问题描述 投票:3回答:1

我的问题类似于这个Get a list of dates between two dates using a function

使用此代码重复10天:

Declare @startDate datetime
Declare @endDate datetime


set @startDate= '03/01/2019 12:00:00'
set @endDate = '04/30/2019 12:00:00'


 ;WITH mycte AS
(
  SELECT CAST(@startDate AS DATETIME) DateValue
  UNION ALL
  SELECT  DateValue + 10
  FROM    mycte   
  WHERE   DateValue + 10 < @endDate - 1
)

SELECT  DateValue
FROM    mycte
OPTION (MAXRECURSION 0)

我得到了ff结果:

2019-03-20 12:00:00.000
2019-03-30 12:00:00.000
2019-04-09 12:00:00.000
2019-04-19 12:00:00.000

但我希望结果如下:

2019-03-20 12:00:00.000
2019-03-30 12:00:00.000
2019-03-31 12:00:00.000
2019-04-09 12:00:00.000
2019-04-10 12:00:00.000
2019-04-20 12:00:00.000
2019-04-21 12:00:00.000
2019-04-30 12:00:00.000

这可能与SQL有关吗?

sql sql-server
1个回答
2
投票

我发现问题相当晦涩,但这似乎做你想要的:

set @startDate= '2019-03-10 12:00:00';
set @endDate = '2019-04-30 12:00:00';


WITH mycte AS (
       SELECT CAST(@startDate AS DATETIME) as DateValue
       UNION ALL
       SELECT CONVERT(DATETIME, EOMONTH(DateValue)) + CONVERT(DATETIME, CONVERT(TIME, DateValue))
       FROM  mycte  
       WHERE MONTH(DateValue + 10) <> MONTH(DateValue) AND
             CONVERT(DATE, DATEVALUE) <> CONVERT(DATE, EOMONTH(DateValue)) AND
             DateValue < @endDate
       UNION ALL
       SELECT DateValue + 10
       FROM mycte
       WHERE DateValue + 10 < @endDate
      )
SELECT DISTINCT DateValue
FROM mycte
ORDER BY DateValue
OPTION (MAXRECURSION 0);

Here是一个db <>小提琴。

© www.soinside.com 2019 - 2024. All rights reserved.