选择2个日期之间的所有月份,并重复每年的结果

时间:2013-04-23 21:28:21

标签: sql-server sql-server-2012 common-table-expression

我需要生成两个日期之间的月份列表,然后重复每年使用 SQL Server 2012 的结果。

以下是一个例子:

  • StartDate = 2010-11-01
  • EndDate = 2011-01-01
  • ReferenceYear = 2008

我想要的结果:

StatDate     StatYearGroup
--------------------------
2007-11-01            2008
2007-12-01            2008
2008-01-01            2008
2008-11-01            2009
2008-12-01            2009
2009-01-01            2009
2009-11-01            2010
2009-12-01            2010
2010-01-01            2010
2010-11-01            2011
2010-12-01            2011
2011-01-01            2011

我可以使用该查询生成2个日期之间的月份列表,但是如何在@endDate和@referenceYear之间重复每年的结果?还有我如何获得StatYearGroup值?

declare @startDate date = '2010-11-01';
declare @endDate date = '2011-01-01';
declare @referenceYear int = 2008;

with dateRange(StatDate) as 
(
    select @startDate
    union all
    select dateadd(month, 1, StatDate)
    from dateRange 
    where StatDate < @endDate
)
select StatDate
from dateRange

1 个答案:

答案 0 :(得分:1)

试试这个 -

DECLARE 
      @startDate DATE = '2010-11-01'
    , @endDate DATE = '2011-01-01'
    , @referenceYear INT = 2008

;WITH rng AS 
(
    SELECT StatDate = @startDate, StatYearGroup = YEAR(@endDate)

    UNION ALL

    SELECT DATEADD(MONTH, 1, StatDate), StatYearGroup
    FROM rng 
    WHERE StatDate < @endDate
), years AS 
(
    SELECT StatDate, StatYearGroup
    FROM rng 

    UNION ALL

    SELECT DATEADD(MONTH, -12, StatDate), StatYearGroup - 1
    FROM years 
    WHERE StatYearGroup > @referenceYear
)
SELECT *
FROM years
ORDER BY StatDate, StatYearGroup