我有一个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中执行此操作。
非常感谢你的帮助。
答案 0 :(得分:3)
在此查询中,内部子查询GRP
使用不同的Driver_id
或Location
对当前记录进行计数,因此对于相同的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)
答案 1 :(得分:-1)
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
可能就是这样,如果我正确理解你。