0

请帮助我如何将日期范围分成一年的几个季度。Ex 日期范围 2012 年 1 月 1 日至 2013 年 10 月 31 日应该给我一个包含所有 8 个季度的结果集。结果应该采用以下格式,我使用的是 SQL 服务器2008 年:

Quarter Month start Month end

1   Jan-12  Mar-12
2   Apr-12  Jun-12
3   Jul-12  Sep-12
4   Oct-12  Dec-12
1   Jan-13  Mar-13
2   Apr-13  Jun-13
3   Jul-13  Sep-13
4   Oct-13  Oct-13
4

2 回答 2

0

您需要查看并以DATEPART(QUARTER,date)这种方式分解它们。类似于这样的东西:

select datepart(year, dateTarget) as theYear, num as theQuarter, min(dateTarget) as startDate, max(dateTarget) as endDate
from numbers
join dates on datepart(quarter, dateper) = num
where num between 1 and 4
group by datepart(year, dateTarget),num

表格在哪里dates是您正在查看的表格,并且numbers是一个数字表格(我发现它非常有用)。

于 2013-03-14T04:24:48.317 回答
-1

这为您提供了 12 个季度的季度开始日期:

with calendar as (
  select 
    --DATEFROMPARTS(year(getdate()),1,1) as [start], 
    convert(datetime, convert(char(4), year(getdate()))+'0101') as [start], 
    qtrsBack = 1
  union all
  select  
    dateadd(mm,-3,[start]), 
    qtrsBack+1
  from calendar
  where qtrsback < 12
)
select * from calendar

生产:

start      qtrsBack
---------- -----------
2013-01-01 1
2012-10-01 2
2012-07-01 3
2012-04-01 4
2012-01-01 5
2011-10-01 6
2011-07-01 7
2011-04-01 8
2011-01-01 9
2010-10-01 10
2010-07-01 11
2010-04-01 12
于 2013-03-14T04:26:48.043 回答