2012-04-04 37 views
1

使用年龄我有一个表在我的PostgreSQL数据库8.4这样的:PostgreSQL中

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; 
+1

'id'是表的主键吗?你能向我们展示一些样本数据吗? – 2012-04-04 07:41:01

+0

我觉得你必须重新思考你的schema.Will它很简单,如果你有事件表中的时间戳记? – sathis 2012-04-04 07:44:37

+0

用示例数据编辑文章和我当前的sql – heldt 2012-04-04 07:47:48

回答

0

我想你需要:

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的第一和最后一个事件之间的间隔。