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

我需要生成两个日期之间的月份列表,然后重复每年的结果,我与SQL Server 2012。选择两个日期之间的所有月份并重复每年的结果

下面是一个例子:

  • 起始日期= 2010-11-01
  • 结束日期= 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

我可以生成mon列表之间的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

回答:

尝试这一个 -

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

以上是 选择两个日期之间的所有月份并重复每年的结果 的全部内容, 来源链接: utcz.com/qa/266098.html

回到顶部