获取两个日期之间的季度和年份

时间:2017-05-22 22:11:29

标签: sql sql-server

我想检索两个日期之间的年份和季度列表。

例如,从2015年12月25日至2017年6月30日,结果应如下所示:

Year    Quarter

2015    4
2016    1
2016    2
2016    3
2016    4
2017    1
2017    2
2017    3

3 个答案:

答案 0 :(得分:2)

您可以使用计数表来执行此操作。

declare @start date='2015-12-25';
declare @end date = '2017-06-30';

select distinct year(dateadd(day,rnum,@start)) yr,
datepart(quarter,dateadd(day,rnum,@start)) qtr
from (select row_number() over(order by (select null)) as rnum 
      from master..spt_values) t
where dateadd(day,rnum,@start) <= @end;

答案 1 :(得分:1)

如果你需要超过6年......几乎与vkp相同(他的速度如此之快!)

Declare @Date1 date = '2015-12-25'
Declare @Date2 date = '2017-06-30'

Select Distinct 
       [Year]   =DatePart(YEAR,D)
      ,[Quarter]=DatePart(QUARTER,D)
 From (
        Select Top (DateDiff(DD,@Date1,@Date2)+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),@Date1) 
         From  master..spt_values n1,master..spt_values n2
      ) A

<强>返回

Year    Quarter
2015    4
2016    1
2016    2
2016    3
2016    4
2017    1
2017    2

答案 2 :(得分:0)

Declare @StartDate Date='2016-01-01'
      , @EndDate Date='2017-05-01'

DECLARE @Date TABLE
(
    [Year] INT,
    [Quarter] INT
)

WHILE @StartDate <= @EndDate
BEGIN   
    INSERT INTO @Date 
    ([Year],
     [Quarter])

SELECT DATEPART(YEAR,@StartDate) AS [Year],
       CASE WHEN DATEPART(MM,@StartDate) BETWEEN 1 AND 3 THEN 1
            WHEN DATEPART(MM,@StartDate) BETWEEN 4 AND 6 THEN 2
            WHEN DATEPART(MM,@StartDate) BETWEEN 7 AND 9 THEN 3
            WHEN DATEPART(MM,@StartDate) BETWEEN 10 AND 12 THEN 4
        END AS [Quarter]
SET     @StartDate = DATEADD(DAY,1,@StartDate)   
END

SELECT DISTINCT [Year],[Quarter] FROM @Date