X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 32FFF9DC811 for ; Thu, 26 Jan 2006 08:11:50 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 74495-07 for ; Thu, 26 Jan 2006 08:11:52 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from mail.metronet.co.uk (mail.metronet.co.uk [213.162.97.75]) by postgresql.org (Postfix) with ESMTP id 0A3C09DC801 for ; Thu, 26 Jan 2006 08:11:47 -0400 (AST) Received: from mainbox.archonet.com (84-51-143-99.archon037.adsl.metronet.co.uk [84.51.143.99]) by smtp.metronet.co.uk (MetroNet Mail) with ESMTP id 13151433754; Thu, 26 Jan 2006 12:09:05 +0000 (GMT) Received: from [192.168.1.17] (client17.office.archonet.com [192.168.1.17]) by mainbox.archonet.com (Postfix) with ESMTP id 57FCF15EE9; Thu, 26 Jan 2006 12:09:12 +0000 (GMT) Message-ID: <43D8BBE7.4050108@archonet.com> Date: Thu, 26 Jan 2006 12:09:11 +0000 From: Richard Huxton User-Agent: Thunderbird 1.5 (X11/20051201) MIME-Version: 1.0 To: "A. Kretschmer" , pgsql-sql@postgresql.org Subject: Re: question with times and intervals References: <20060126115816.GA9924@webserv.wug-glas.de> In-Reply-To: <20060126115816.GA9924@webserv.wug-glas.de> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.098 required=5 tests=[AWL=0.098] X-Spam-Score: 0.098 X-Spam-Level: X-Archive-Number: 200601/181 X-Sequence-Number: 23970 A. Kretschmer wrote: > Hi, > > I have a table like this: > > test=# select * from status_log ; > id | status | t_start | t_end > ----+--------+------------------------+------------------------ > 1 | 1 | 2006-01-20 23:00:00+01 | 2006-01-21 06:00:00+01 > 1 | 1 | 2006-01-21 06:00:00+01 | 2006-01-21 22:00:00+01 > 1 | 2 | 2006-01-21 22:00:00+01 | 2006-01-22 05:00:00+01 > 1 | 1 | 2006-01-22 05:00:00+01 | 2006-01-22 15:00:00+01 > 1 | 2 | 2006-01-22 15:00:00+01 | 2006-01-23 02:00:00+01 > (5 rows) > > Now i need for a particular intervall (one day or two days, entires > days) the accumulated time for id=X and status=Y. > > Exampel: > > id=1, status=1, date=2006-01-21: > > from 00:00:00 - 06:00:00 and > 06:00:00 - 22:00:00 > > ===> 6 hours + 16 hours = 22 hours OK - all untested... First step - don't ask for a date, ask between two timestamptz's (which I'll call t1, t2) Then, define two functions: earlier(timestamptz, timesatmptz) and later(...) as SQL functions using SELECT ... CASE SELECT later(T1, t_start) AS lower_time earlier(T2, t_end) AS upper_time FROM status_log WHERE id = X AND status = Y AND ts_end >= T1 AND ts_start <= T2 ; Now (upper_time - lower_time) is the interval you want and summing them will give you your answer. Any help? -- Richard Huxton Archonet Ltd