Received: from localhost (maia-5.hub.org [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 5E7A19FBC4B for ; Wed, 13 Jun 2007 15:41:01 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-maia, port 10024) with ESMTP id 04572-06-2 for ; Wed, 13 Jun 2007 15:40:45 -0300 (ADT) X-Greylist: delayed 02:30:54.377473 by SQLgrey-1.7.4 Received: from ganymede.ibss.net (66.49.75.50.nw.nuvox.net [66.49.75.50]) by postgresql.org (Postfix) with ESMTP id 776679FBC28 for ; Wed, 13 Jun 2007 15:40:53 -0300 (ADT) Received: from [172.23.1.200] (jumper.ibss.net [172.23.1.200]) by ganymede.ibss.net (8.13.6/8.13.4) with ESMTP id l5DIeiT7013084; Wed, 13 Jun 2007 14:40:45 -0400 Message-ID: <46703C0F.9080506@ibss.net> Date: Wed, 13 Jun 2007 14:48:47 -0400 From: Bob Singleton User-Agent: Thunderbird 1.5.0.10 (X11/20070302) MIME-Version: 1.0 To: =?ISO-8859-1?Q?Rodrigo_De_Le=F3n?= CC: pgsql-sql@postgresql.org Subject: Re: calculate time diffs across rows with single timestamp References: <467018B0.30108@ibss.net> <1181753515.419178.63440@j4g2000prf.googlegroups.com> In-Reply-To: <1181753515.419178.63440@j4g2000prf.googlegroups.com> Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Virus-Scanned: ClamAV version 0.90.3, clamav-milter version 0.90.3 on ganymede.ibss.net X-Virus-Status: Clean X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.324 tagged_above=0 required=5 tests=AWL=-0.188, BAYES_50=0.001, FORGED_RCVD_HELO=0.135, HTML_30_40=0.374, HTML_MESSAGE=0.001, MIME_HTML_ONLY=0.001, UPPERCASE_25_50=0 X-Spam-Level: X-Archive-Number: 200706/95 X-Sequence-Number: 28585 Rodrigo De León wrote:
On Jun 13, 11:17 am, bsingle...@ibss.net (Bob Singleton) wrote:
  
Any suggestions on how I can build a result set that would return

ASSET 001 AAA 1:00 (1 hour)
ASSET 001 BBB 0:10 (10 minutes)
ASSET 001 CCC 0:08 (8 minutes)
ASSET 001 DDD {difference between timestamp and now()}
ASSET 002 AAA 0:03 (3 minutes)
ASSET 002 BBB {difference detween timestamp and now()}
ASSET 003 AAA{diff between timestamp and now()}
    

SELECT
TYPE, ID, STATUS
, (COALESCE(
	(SELECT MIN(DATETIME) FROM STATUSLOG
	WHERE TYPE = S.TYPE AND ID = S.ID AND DATETIME > S.DATETIME)
	, NOW()::TIMESTAMP
	) - DATETIME) AS DURATION
FROM STATUSLOG S
ORDER BY TYPE, ID, STATUS


---------------------------(end of broadcast)---------------------------
TIP 6: explain analyze is your friend

  
Awesome - thank you very much! Slightly modified to collapse by TYPE / ID / STATUS

SELECT
TYPE, ID, STATUS, SUM(
    (COALESCE(
	(SELECT MIN(DATETIME) FROM STATUSLOG
	WHERE TYPE = S.TYPE AND ID = S.ID AND DATETIME > S.DATETIME)
	, NOW()::TIMESTAMP
	) - DATETIME))
FROM STATUSLOG S
ORDER BY TYPE, ID, STATUS

Thanks for the lesson!

Bob Singleton