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 558539DC823 for ; Wed, 21 Dec 2005 06:20:15 -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 94564-04 for ; Wed, 21 Dec 2005 06:20:16 -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 20CFF9DC820 for ; Wed, 21 Dec 2005 06:20:13 -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 F1BB840DC85; Wed, 21 Dec 2005 10:04:44 +0000 (GMT) Received: from [192.168.1.17] (client17.office.archonet.com [192.168.1.17]) by mainbox.archonet.com (Postfix) with ESMTP id 6EB0015EA4; Wed, 21 Dec 2005 10:04:50 +0000 (GMT) Message-ID: <43A928C2.8060901@archonet.com> Date: Wed, 21 Dec 2005 10:04:50 +0000 From: Richard Huxton User-Agent: Thunderbird 1.5 (X11/20051025) MIME-Version: 1.0 To: Matthew Smith Cc: pgsql-sql@postgresql.org Subject: Re: Help on a complex query (avg data for day of the week) References: <200512191657.48139.mps@utas.edu.au> In-Reply-To: <200512191657.48139.mps@utas.edu.au> 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.019 required=5 tests=[AWL=0.019] X-Spam-Score: 0.019 X-Spam-Level: X-Archive-Number: 200512/192 X-Sequence-Number: 23734 Matthew Smith wrote: > I want to form a query that returns the average total usage for each day of > the week, eg: [snip] > To get this info, I am using the following query: > > select dow as day, sum(sum_data)/count(dow) as avg_usage from > (select extract('dow' from date_trunc('day', time)) as dow, sum(data) as > sum_data > from datalog where time >= '2005-09-11' and time <= '2005-09-25' group by dow) > as avg_data_per_day group by day; > > This works well, assuming that there is at least one entry in the table for > each day in the time period. > > The problem comes when there are days where no data is logged. 1. Calculate how many data-points each day represents 2. Sum the days you do have data for 3. Left-join #1 to #2 so you can calculate the average. I'm guessing for #1 you'd rather not have 7 UNIONs, so you might find generate_series() a useful function. See Ch 9.18. Set Returning Functions. HTH -- Richard Huxton Archonet Ltd