我有一张桌子可以跟踪车辆进出的时间表。
Table: Schedule
route location v_type out in
===================================================================
a loc1 10 2/14/2013 08:04:00 2/14/2013 10:03:00
b loc1 11 2/14/2013 08:06:00 2/14/2013 14:20:00
c loc2 11 2/14/2013 06:22:00 2/14/2013 07:50:00
d loc1 10 2/14/2013 11:04:00 2/14/2013 10:03:00
e loc2 10 2/14/2013 08:06:00 2/14/2013 14:20:00
f loc2 11 2/14/2013 06:22:00 2/14/2013 07:50:00
想象一下,但每天有数千条路线。我试图找出每个位置,并且v_type大多数车辆在路上的时间(或时间窗口)。
期望的结果,例如
location v_type time peak
===========================================
loc1 10 2/14/2013 10:40 110
loc1 11 2/14/2013 10:30 80
loc2 10 2/14/2013 08:05 67
loc2 11 2/14/2013 09:45 107
等。
基本思路是,您可以通过查找已离开的车辆总数,并减去当天返回的车辆数量,在任何时间点找到道路上的车辆数量。
这是我到目前为止所做的,但是它没有完全正确地工作,并且很慢。
SELECT s.location,
s.v_type,
TO_CHAR(TRUNC(s.out, 'mi') - mod(EXTRACT(minute FROM CAST(s.out AS TIMESTAMP)), 10) / (24 * 60), 'YYYY-MM-DD HH24:MI') AS TIME,
(SELECT
(SELECT COUNT(*)
FROM SCHEDULE s2
WHERE s2.out BETWEEN TRUNC(s.out) AND (TRUNC(s.out, 'mi') - mod(EXTRACT(minute FROM CAST(s.out AS TIMESTAMP)), 10) / (24 * 60))
)
-
(SELECT COUNT(*)
FROM SCHEDULE s2
WHERE s2.out BETWEEN TRUNC(s.in) AND (TRUNC(s.in, 'mi') - mod(EXTRACT(minute FROM CAST(s.in AS TIMESTAMP)), 10) / (24 * 60))
)
FROM dual
)
FROM SCHEDULE s
GROUP BY s.location, s.v_type,
(TRUNC(s.out, 'mi') - mod(EXTRACT(minute FROM CAST(s.out AS TIMESTAMP)), 10) / (24 * 60))
答案 0 :(得分:0)
我会将此视为累积金额之间的差异:
select s.*
from (select s.*, (numout - numin) as onroad,
row_number() over (partition by loc, vtype order by numout - numin desc) as seqnum
from (select s.*,
(select count(*) from schedule s2 where s2.loc = s.loc and s2.vtype = s.vtype and s2.out <= s.out
) as numout,
(select count(*) from schedule s2 where s2.loc = s.loc and s2.vtype = s.vtype and and s2.in <= s.out
) as numin
from schedule s
) s
) s
where seq = 1
您也可以使用分析函数执行此操作,但相关子查询可能更容易编写。此外,你开始沿着这条道路前进。