SQL 从日期列表中查询 return 个季度日期

SQL query to return quarterly dates from list of dates

有人可以帮我 SQL 查询吗?我有一个 table 有这样的数据

期间table:

ID
StartDate
EndDate

数据将如下所示:

1 1/3/2017 2/2/2017
2 2/3/2017 3/2/2017
3 3/3/2017 4/2/207
4 4/3/2017 5/2/2017
5 5/3/2017 6/2/2017
6 6/3/2017 7/2/2017
7 7/3/2017 8/2/2017
8 8/3/2017 9/2/2017
9 9/3/2017 10/2/2017

...

我想编写一个 SQL 查询,其中 returns 以下 3 列:

9,8,7 | 7/3/2017 | 10/2/2017
6,5,4 | 4/3/2017 | 7/2/2017
3,2,1 | 1/3/2017 | 4/2/2017

下面的 SQL 使用 xml 路径技巧将 Id 折叠到列表中,按季度分组。

select 
stuff(
 (select concat(',',tid.ID)
  from PeriodTable tid
  where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
    and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
  for xml path(''), type).value('.', 'varchar(max)')
 ,1,1,'') IdList,
min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;

或者使用交叉应用的方法的这种变体:

select 
stuff(max(Ids),1,1,'') as IdList, min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
cross apply (
   select concat(',',tid.ID)
   from PeriodTable tid
   where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
     and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
   for xml path('')) List(Ids)
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;

试一试here on rextester