按类别相同的名称分组,但类别的含义不同

时间:2015-07-21 14:17:11

标签: sql sql-server-2012 group-by

我有一张表格如下

start_date end_date category

26/05/2015 10:05 26/05/2015 10:10 d

26/05/2015 10:17 26/05/2015 10:20 d

26/05/2015 10:35 26/05/2015 10:44 c

26/05/2015 10:50 26/05/2015 10:57 c

26/05/2015 11:05 26/05/2015 11:13 d

26/05/2015 11:27 26/05/2015 11:30 d

我需要按类别进行分组并采用min(start_date)和max(end_date),但如果没有类别序列则具有不同的含义。

我想得到像这样的结果

start_date end_date category

26/05/2015 10:05 26/05/2015 10:20 d

26/05/2015 10:35 26/05/2015 10:57 c

26/05/2015 11:05 26/05/2015 11:30 d

谢谢大家

2 个答案:

答案 0 :(得分:2)

您可以通过为每组连续行分配一个组标识符来实现此目的,其中值相同。我喜欢用行数区别来做这个:

select min(start_date) as start_date, max(end_date) as end_date, category
from (select t.*,
             (row_number() over (order by start_date) -
              row_number() over (partition by category order by start_date)
             ) as grp
      from table t
     ) t
group by category, grp;

答案 1 :(得分:0)

另一种选择,添加标识列并使用递归CTE:

;with CTE (ID,st_date,end_date,category,group_no) as
(select ID,st_date,end_date,category,1 as group_no
 from dates d
 where ID = 1
 union all
 select d.ID,d.st_date,d.end_date,d.category
 ,case when d.category = cte.category then cte.group_no else cte.group_no + 1 end
 from dates d
 inner join CTE cte on d.ID - 1= cte.ID
 )

 select MIN(st_date) as st_date,MAX(end_date) as end_date,category from CTE
 group by group_no,category
 order by st_date asc

[http://sqlfiddle.com/#!3/261c3]