From: Steve Crawford <scrawford@pinpointresearch.com>
To: Andreas <maps.on@gmx.net>
Cc: pgsql-sql@postgresql.org
Subject: Re: how to calculate differences of timestamps?
Date: Tue, 27 Sep 2011 09:08:38 -0700
Message-ID: <4E81F506.6010604@pinpointresearch.com> (raw)
In-Reply-To: <4E812787.1080002@gmx.net>
References: <4E812787.1080002@gmx.net>
On 09/26/2011 06:31 PM, Andreas wrote:
> How could I calculate differences of timestamps in a log-table?
>
> Table log ( user_id integer, login boolean, ts timestamp )
>
> So login = true would be a login-event and login = false a logout.
> Is there a way to find the matching login/logout to calculate the
> difference?
>
> Or is there a better table "design" to do this?
>
One way is a sub_select:
select
o.user_id,
o.ts as logout_time,
(select
max(i.ts)
from
log i
where
i.user_id = o.user_id and
i.ts < o.ts and
login
) as login_time
from
log
where
not login
;
This will give you login/logout time pairs. Just replace the "," with a
"-" if you are interested in login duration.
Depending on the frequency and duration of logins and the number of
users you may have to play with indexes though an index on ts will
probably suffice for most cases.
Cheers,
Steve
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: scrawford@pinpointresearch.com, maps.on@gmx.net
Subject: Re: how to calculate differences of timestamps?
In-Reply-To: <4E81F506.6010604@pinpointresearch.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox