我的postgresql 8.4数据库中有一个表如下:

id(serial), event_type_id(id, foreign key), ts(timestamp)

我有两个事件类型的id,我需要查看两者之间的年龄。
Event_type_id 1 = Arrive
Event_type_id 2 = Leaves

示例数据
 id | event_type_id |             ts
----+---------------+----------------------------
 21 |             6 | 2012-04-03 16:02:18.739274
 20 |             5 | 2012-04-03 08:44:13.244287

我想按天分组,看看每天有多少小时。
有人能告诉我怎么分组和计算年龄吗?
到目前为止我已经有了这个,但是我需要生成一个系列来加入或者类似的东西
解决方案
不知道这是不是最好的做法,但它对我有效。
SELECT dx, age(max(ts), min(ts))
from generate_series('2012-04-01', '2012-04-14', interval '1 day') as dx
left join events on (ts >= dx and ts < dx + '23 hours 59 minutes' and event_type_id in (5,6))
group by dx
order by dx;

最佳答案

我认为你需要:

select age(max(ts), min(ts)), ts::date as date
from events
where event_type_id in (5,6)
group by date;

但你的问题还不清楚。我想你的意思是你有一个这样的表(不是数据库):
create table events (
  id serial,
  event_type_id int references event_types,
  ts timestamp
);

您需要为每个日期计算类型5或6的第一个事件和最后一个事件之间的间隔。

10-07 14:01
查看更多