X-Original-To: pgsql-sql@postgresql.org Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id EF24D476075 for ; Tue, 4 Mar 2003 06:14:22 -0500 (EST) Received: from postgresql.org ([64.49.215.8]) by localhost (postgresql.org [64.49.215.8:10024]) (amavisd-new) with SMTP id 64919-10 for ; Tue, 4 Mar 2003 06:14:18 -0500 (EST) Received: from fzkmail2.fzk.de (fzkmail2.fzk.de [141.52.27.52]) by postgresql.org (Postfix) with SMTP id B8680476074 for ; Tue, 4 Mar 2003 06:14:17 -0500 (EST) Received: FROM resy5.fzk.de BY fzkmail2.fzk.de ; Tue Mar 04 12:14:19 2003 +0100 Received: œby rodos.fzk.de with ESMTP (8.8.6 (PHNE_17135)/8.7.1) id MAA18165; Tue, 4 Mar 2003 12:14:18 +0100 (MET) Message-ID: <3E648A8A.91C289CB@rodos.fzk.de> Date: Tue, 04 Mar 2003 12:14:18 +0100 From: Christoph Haller X-Mailer: Mozilla 4.77 [en] (X11; U; HP-UX B.10.20 9000/780) X-Accept-Language: en MIME-Version: 1.0 To: pgsql-sql@postgresql.org Cc: Mark.Connelly@ntl.com Subject: Re: using Avg() Content-Type: text/plain; charset=iso-8859-2 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new X-Archive-Number: 200303/112 X-Sequence-Number: 12152 > > I have a table with a column named SwErr (Switch Error) with int values > date with datetime values and SwID with char(3) > I am trying to get a subset back where the folowing is true > > select the avg(SwErr) for the last 30 days where SwId = 'XX1' > Select the value of todays value of SwErr where SwId = 'XX1' > if todays value of SwErr is greater than 4 times the SwErr Average return in > the value > Looks like you could use a plpgsql function, something like (untested) CREATE OR REPLACE FUNCTION get_dated_SwErr(CHAR) RETURNS INTEGER AS ' DECLARE thisSwID ALIAS FOR $1; todaysSwErr INT; avgSwErr INT; avg4SwErr INT; dateLimit TIMESTAMP; BEGIN SELECT INTO dateLimit current_date - ''30 days''::interval ; SELECT INTO todaysSwErr SwErr FROM WHERE SwID = thisSwID AND SwDate = current_date ; SELECT INTO avgSwErr AVG(SwErr)::int FROM WHERE SwID = thisSwID AND SwDate BETWEEN current_date AND dateLimit ; avg4SwErr := avgSwErr * 4 ; IF todaysSwErr > avg4SwErr THEN RETURN todaysSwErr; ELSE RETURN avgSwErr; END IF; END; ' LANGUAGE 'plpgsql' ; then SELECT SwID, get_dated_SwErr(SwID) FROM WHERE SwID = 'XX1' AND SwDate = current_date ; should bring up the result. Regards, Christoph