SQL - 按问题分组

时间:2012-01-26 12:32:44

标签: sql sql-server sql-server-2008 sql-server-2005

我有一个表格中有记录(简化):ID(int),startTime(DateTime),endTime(DateTime)

我希望能够将按时间间隔“重叠”的记录分组。 例如:

1 - 12.00.AM - 12.10.AM ( duration here is 10 min)
2 - 12.05.AM - 12.07.AM (duration here is 2 minutes but is overlapping with record ID = 1 in minutes 05, 06, 07)

The result of such a query should be 
minute 12.00 - record 1, 
minute 12.01 - record 1, 
... 
minute 12.05 - record 1 + record 2, 
minute 12.06 - record 1 + record 2, 
minute 12.07 - record 1 + record 2 
... 
minute 12.10 - record 1

注意我使用sql server(2005 uppwards)

1 个答案:

答案 0 :(得分:2)

这是在Oracle中实现它的一种方法(11g第2版,因为它包含LISTAGG函数):

with CTE as
       (    select STRT + (rownum - 1) / 24 / 60 as TIMES
              from (select min(STARTTIME) as STRT from FORM1)
        connect by level <=
                     (select (max(ENDTIME) - min(STARTTIME)) * 24 * 60
                        from FORM1))
  select to_char(CTE.TIMES, 'hh24:mi') as MINUTE
        ,LISTAGG(ID, ',') within group (order by ID) as IDS
    from   CTE
         join
           FORM1
         on CTE.TIMES <= FORM1.ENDTIME and CTE.TIMES >= FORM1.STARTTIME
group by to_char(CTE.TIMES, 'hh24:mi')
order by to_char(CTE.TIMES, 'hh24:mi')

我使用的测试数据是:

create table FORM1
(
  ID          number
 ,STARTTIME   date
 ,ENDTIME     date
);

insert into FORM1
     values (
              1
             ,to_date('26/01/2012 00:00:00', 'dd/mm/yyyy hh24:mi:ss')
             ,to_date('26/01/2012 00:10:00', 'dd/mm/yyyy hh24:mi:ss'));

insert into FORM1
     values (
              2
             ,to_date('26/01/2012 00:05:00', 'dd/mm/yyyy hh24:mi:ss')
             ,to_date('26/01/2012 00:07:00', 'dd/mm/yyyy hh24:mi:ss'));

我得到以下结果:

Minute  IDs
00:00   1
00:01   1
00:02   1
00:03   1
00:04   1
00:05   1,2
00:06   1,2
00:07   1,2
00:08   1
00:09   1