Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 897D9B5F461 for ; Tue, 27 Sep 2011 13:37:13 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 39311-02 for ; Tue, 27 Sep 2011 16:37:07 +0000 (UTC) X-Greylist: delayed 00:19:15.366748 by SQLgrey-1.8.0-rc2 Received: from polaris.pinpointresearch.com (cerberus.pinpointresearch.com [66.7.238.130]) by mail.postgresql.org (Postfix) with ESMTP id DA279B5F7CF for ; Tue, 27 Sep 2011 13:27:55 -0300 (ADT) Received: from betelgeuse.pinpointresearch.com (betelgeuse.pinpointresearch.com [192.168.1.179]) by polaris.pinpointresearch.com (Postfix) with ESMTP id 7EB44E00EC83; Tue, 27 Sep 2011 09:08:38 -0700 (PDT) Message-ID: <4E81F506.6010604@pinpointresearch.com> Date: Tue, 27 Sep 2011 09:08:38 -0700 From: Steve Crawford User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.21) Gecko/20110831 Lightning/1.0b2 Thunderbird/3.1.13 MIME-Version: 1.0 To: Andreas CC: pgsql-sql@postgresql.org Subject: Re: how to calculate differences of timestamps? References: <4E812787.1080002@gmx.net> In-Reply-To: <4E812787.1080002@gmx.net> Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.404 tagged_above=-5 required=5 tests=BAYES_00=-1.9, RP_MATCHES_RCVD=-0.504 X-Spam-Level: X-Archive-Number: 201109/83 X-Sequence-Number: 35883 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