SQL查询从日期列表返回季度日期

时间:2017-07-09 04:01:12

标签: sql-server stored-procedures sql-query-store

有人可以帮我解决SQL查询吗?我有一张表有这样的数据

Periodtable

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

...

我想编写一个返回以下3列的SQL查询:

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

1 个答案:

答案 0 :(得分:1)

下面的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;

试试here on rextester