对记录进行分组

Posted

技术标签:

【中文标题】对记录进行分组【英文标题】:Grouping the records 【发布时间】:2013-08-16 07:08:02 【问题描述】:

我有一个 vehicle_fact 表,其中包含字段 start_Date_Time、end_date_time、location 和 driver_id。我的目标是根据 driver_id 和位置获取停止计数、开始日期、结束日期。

表格如下,

start_Date_Time          end_date_time            LOCATION  driver_id
---------------          -------------            --------  ---------
11/08/2013 06:51:53      11/08/2013 07:06:50         loc1        2
11/08/2013 09:00:15      11/08/2013 09:16:37         loc2        2
11/08/2013 09:41:16      11/08/2013 09:50:03         loc1        2
11/08/2013 09:53:28      11/08/2013 10:01:27         loc1        2
11/08/2013 10:41:31      11/08/2013 10:45:45         loc2        2
11/08/2013 11:25:54      11/08/2013 11:38:55         loc1        2
11/08/2013 14:45:08      11/08/2013 14:54:52         loc2        3
11/08/2013 15:20:45      11/08/2013 15:28:29         loc2        3
11/08/2013 15:30:39      11/08/2013 15:31:59         loc1        3
11/08/2013 16:25:24      11/08/2013 16:25:35         loc1        3
11/08/2013 20:26:35      12/08/2013 01:51:19         loc1        3

期望的结果应该是:

start_Date_Time          end_date_time            LOCATION  driver_id count
11/08/2013 06:51:53      11/08/2013 07:06:50      loc1      2         1
11/08/2013 09:00:15      11/08/2013 09:16:37      loc2      2         1
11/08/2013 09:41:16      11/08/2013 10:01:27      loc1      2         2
11/08/2013 10:41:31      11/08/2013 10:45:45      loc2      2         1
11/08/2013 11:25:54      11/08/2013 11:38:55      loc1      2         1
11/08/2013 14:45:08      11/08/2013 15:28:29      loc2      3         2
11/08/2013 15:30:39      12/08/2013 01:51:19      loc1      3         3

是否可以在 SQL 中完成。

非常感谢您的帮助。

【问题讨论】:

无论你在前端使用了什么逻辑,都可以在Stored Procedure 中框定。对不起,我不是转换器。 停机次数是什么意思? 嗨 Bew,这是车辆怠速计数(当点火开关关闭时)。 【参考方案1】:

在此查询中,内部子查询 GRP 计算当前之前具有不同 Driver_idLocation 的记录,因此对于相同的 Driver_id,Location 记录,我们得到相同的 GRP 计数。然后我们只需按Driver_id,Location 和 GRP 分组。

select min(START_DATE_TIME),
       Max(END_DATE_TIME),
       LOCATION,
       DRIVER_ID,
       count(*) cnt
FROM
(
select t1.*,
(select count(*) 
  from vehicle_fact t2
  where (t2.End_date_time<t1.End_date_time)
    and 
    (
     (t2.location<>t1.location)
      OR
     (t2.driver_id <>t1.driver_id )
    )  
) Grp

from vehicle_fact t1
) T3

GROUP BY LOCATION,DRIVER_ID,GRP
  order by min(START_DATE_TIME) 

SQLFiddle demo

【讨论】:

【参考方案2】:
select start_Date_Time, end_date_time, LOCATION, driver_id
,    (select count(*) 
      from table t2
      where
           t1.driver_id=t2.driver_id
      and  t1.LOCATION=t2.LOCATION
      )
from table t1
order by t1.driver_id asc

可能是这样,如果我理解正确的话。

【讨论】:

以上是关于对记录进行分组的主要内容,如果未能解决你的问题,请参考以下文章

Oracle sql查询按日期对连续记录进行分组

对相关记录进行分组,但仅从第一条记录中选择某些字段

对记录进行分组

在 Master 中对记录进行分组,但希望对 Details 进行计数

如何按 MySQL 中的最后一个重复项对记录进行分组?

计算记录并按小时对它们进行分组