列出两个日期之间的日期

时间:2017-11-17 07:48:06

标签: sql sql-server

我想知道是否有办法使用sql输出列表日期开始日期结束年份+ 1间隔(有闰年)如下:

Date_start 2014-06-01 00:00:00 Date_End 2017-05-31 00:00:00

select '2014-06-01 00:00:00',dateadd(DAY, 365, '2014-06-01 00:00:00')

2014-06-01 00:00:00 2015-06-01 00:00:00
2015-06-01 00:00:00 2016-05-31 00:00:00
2016-05-31 00:00:00 2017-05-31 00:00:00

2 个答案:

答案 0 :(得分:1)

试试吧

DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(YEAR,1,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(YEAR,1,EndDate)<@MaxDate,DATEADD(YEAR,1,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(YEAR,1,EndDate)<@MaxDate THEN DATEADD(YEAR,1,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);

变体DATEADD(DAY,365,...)

DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(DAY,365,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(DAY,365,EndDate)<@MaxDate,DATEADD(DAY,365,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(DAY,365,EndDate)<@MaxDate THEN DATEADD(DAY,365,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);

答案 1 :(得分:0)

试试这个

DECLARE @StartDate  DATE='15 JAN 2011',
        @EndDate    DATE='31 DEC 2018'


;WITH CTE_DATE AS
(
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,@StartDate),@StartDate)) [START_DATE],
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,@StartDate)),DATEADD(MM,1,@StartDate)) END_DATE
    UNION ALL
    SELECT  DATEADD(DD,1,DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,[START_DATE])),DATEADD(MM,1,[START_DATE]))) [START_DATE], 
            DATEADD(DD,-DATEPART(DD,DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))),DATEADD(MM,1,DATEADD(MM,1,[START_DATE]))) END_DATE 
    FROM CTE_DATE   
    WHERE END_DATE<@EndDate
)

SELECT * FROM CTE_DATE