Count distinct sql and break by day with timestamp over midnight

时间:2016-02-12 22:13:30

标签: sql postgresql

I have a time series of data that has a right click and time stamp. I'm trying to write a SQL query to give me the number of unique trip_id that occur on one day.

The problem is that the trip's extend across midnight, as the next day comes the trip is treated as a new distinct value and counted twice using this code trip_id's . Any help or the appropriate point in the correct direction would be very much appreciated.

Data:

select date(Timestamp), COUNT(DISTINCT trip_id)

Desired Outcome

trip_id    Timestamp
47585      "2015-11-05 09:22:23"
16935      "2015-11-05 12:34:28"
16935      "2015-11-05 20:40:28"
16935      "2015-11-05 23:09:24"
16935      "2015-11-05 23:21:58"
16935      "2015-11-06 00:22:05"
15434      "2015-11-06 21:23:28"

1 个答案:

答案 0 :(得分:1)

使用每次旅行的最短时间戳:

select dte, count(*)
from (select trip_id, min(date_trunc('day', timestamp)) as dte
      from t
      group by trip_id
     ) t
group by dte
order by dte;

即计算行程开始的日期。