Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 82845B5DBC8 for ; Mon, 26 Sep 2011 23:57:41 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 73078-09 for ; Tue, 27 Sep 2011 02:57:35 +0000 (UTC) X-Greylist: delayed 00:15:03.00915 by SQLgrey-1.8.0-rc2 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id 08844B5DC00 for ; Mon, 26 Sep 2011 23:57:34 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1R8Ncs-0006DB-Nr for pgsql-sql@postgresql.org; Tue, 27 Sep 2011 04:42:30 +0200 Received: from d177189.adsl.hansenet.de ([80.171.177.189]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 27 Sep 2011 04:42:30 +0200 Received: from tim by d177189.adsl.hansenet.de with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 27 Sep 2011 04:42:30 +0200 X-Injected-Via-Gmane: http://gmane.org/ Mail-Followup-To: pgsql-sql@postgresql.org To: pgsql-sql@postgresql.org From: Tim Landscheidt Subject: Re: how to calculate differences of timestamps? Date: Tue, 27 Sep 2011 02:42:16 +0000 Organization: Lines: 33 Message-ID: References: <4E812787.1080002@gmx.net> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: d177189.adsl.hansenet.de Mail-Copies-To: never User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:zJzVMlu81PCU91jDOCaMghlbHWo= 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/82 X-Sequence-Number: 35882 (anonymous) 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? This is similar to the question Dianna asked some time ago: | SELECT user_id, | prev_ts AS login_ts, | ts AS logout_ts | FROM (SELECT user_id, | LAG(login) OVER (PARTITION BY user_id ORDER BY ts) AS prev_login, | LAG(ts) OVER (PARTITION BY user_id ORDER BY ts) AS prev_ts, | login, | ts FROM log) AS SubQuery | WHERE prev_login AND NOT login; > Or is there a better table "design" to do this? That depends on your requirements and your application de- sign. The query above requires a full table scan which may kill performance in some circumstances. Of course, any design has to deal with the possibility of an event not having been logged, multiple logins, etc. The query above just forms pairs based on temporal proximity. Tim