Re: Aggregate query for multiple records

From: Josh Berkus <josh(at)agliodbs(dot)com>
To: Scott Gerhardt <scott(at)g-it(dot)ca>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Aggregate query for multiple records
Date: 2004-08-27 15:43:32
Message-ID: 200408270843.32059.josh@agliodbs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Scott,

> > SELECT wid,
> > (SELECT SUM(oil) FROM prd_data pd2
> > WHERE pd2.wid = prd_data.wid ORDER BY "date" LIMIT 6) as tot_oil,
> > (SELECT SUM(hours) FROM prd_data pd2
> > WHERE pd2.wid = prd_data.wid ORDER BY "date" LIMIT 6) as tot_hours
> > FROM prd_data
> > ORDER BY wid;
>
> There is only one table being queried (prd_data). What is the purpose
> of "pd2"?

It's a table alias. There may be only one table, but to do this in a single
query you need to reference 3 "instances" of that same table.

Hmmm ... let me make the distinction more clear:

SELECT wid,
(SELECT SUM(oil) FROM prd_data prd2
WHERE prd2.wid = prd1.wid ORDER BY "date" LIMIT 6) as tot_oil,
(SELECT SUM(hours) FROM prd3
WHERE prd3.wid = prd1.wid ORDER BY "date" LIMIT 6) as tot_hours
FROM prd_data prd1
ORDER BY wid;

--
Josh Berkus
Aglio Database Solutions
San Francisco

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2004-08-27 16:02:20 Re: from PG_DUMP to CVS
Previous Message Nosyman 2004-08-27 15:30:32 GRANT ON all tables