下面的 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;
或者使用 CROSS APPLY 的方法的这种变体:
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;
在 rextester 上试试