0

我需要生成 2 个日期之间的月份列表,然后重复我在SQL Server 2012中拥有的每一年的结果。

这是一个例子:

  • 开始日期 = 2010-11-01
  • 结束日期 = 2011-01-01
  • 参考年 = 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

我可以使用该查询生成两个日期之间的月份列表,但是我如何在@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
4

1 回答 1

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
于 2013-04-24T06:38:36.773 回答