SQL列表中两个日期之间的重复日期,结束日期为下一个开始日期

时间:2019-03-22 17:56:44

标签: sql sql-server

我的问题与此类似 Moment

重复使用此代码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)

我得到了结果:

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可能吗?

1 个答案:

答案 0 :(得分: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 <>小提琴。