我有一张桌子,可以在不同的时间进入每辆车。
vehicle_ id time place
____________ _____ ________
1 2016-09-01 10:00:00 10
2 2016-09-01 10:00:00 12
1 2016-09-01 10:01:00 10
1 2016-09-01 10:01:10 10
3 2016-09-01 10:02:00 15
2 2016-09-01 10:03:00 18
1 2016-09-01 10:03:00 12
2 2016-09-01 10:04:00 10
2 2016-09-01 10:05:00 10
1 2016-09-01 10:06:00 15
2 2016-09-01 10:07:00 18
3 2016-09-01 10:09:00 19
4 2016-09-01 11:06:00 15
1 2016-09-01 11:07:00 18
3 2016-09-01 11:09:00 19
4 2016-09-01 11:10:00 15
2 2016-09-01 11:11:00 18
6 2016-09-01 11:12:00 19
4 2016-09-01 11:16:00 15
5 2016-09-01 11:17:00 18
3 2016-09-01 11:19:00 19
我想知道有多少车辆从一个时间段开始发送数据?例如从10:00到11:00 3辆车开始发送信号,车辆1从10号站开始,车辆2从从地点15到12和车辆3.从11:00到12:00,车辆4从地方15开始,车辆5从地方18开始,车辆6从地方19开始。
所以最后的输出将是
For 10-11
place vehicle_count
_____ _____________
10 1
12 1
15 1
For 11-12
place vehicle_count
_____ _____________
15 1(vehicle_id 4)
18 1(vehicle_id 5)
19 1(vehicle_id 6)
For 10-12
place vehicle_count
_____ _____________
10 1(vehicle_id 1)
12 1(vehicle_id 2)
15 2(vehicle_id 3,4)
18 1(vehicle_id 5)
19 1(vehicle_id 6)
我做了
select count(distinct(vehicle_id)) from public.datatable where time>=2016-09-01 10:00:00 and time<2016-09-01 11:00:00
但是这给了所有地方的计数,但是如何只获得原点地方。(这意味着车辆ID 1来自地方10,所以它应该只计算在地方10下)。感谢任何帮助
答案 0 :(得分:0)
您可以使用distinct on
在该时间段内获取每辆车的第一个位置,然后汇总以获取place
:
select place, count(*)
from (select distinct on (vehicle_id) dt.*
from public.datatable dt
where time >= '2016-09-01 10:00:00' and time < '2016-09-01 11:00:00'
order by vehicle_id, time
) v
group by place;
答案 1 :(得分:0)
您需要的是GROUP BY:
select place, count(*)
from public.datatable
where
time>=2016-09-01 10:00:00 and
time<2016-09-01 11:00:00
GROUP BY place
答案 2 :(得分:0)
select place,
count( distinct vehicle_id) from t t1
where
tim>=to_date('2016-09-01 10:00:00','yyyy-mm-dd HH:MI:SS') and
tim<to_date('2016-09-01 12:00:00','yyyy-mm-dd HH:MI:SS')
and not exists (select * from t t2 where t1.tim >t2.tim and t1.vehicle_id=t2.vehicle_id)
group by t1.place
order by t1.place;