group by with multiple selects having different where conditions

From: Benjamin Franks <benjamin(at)dzhan(dot)com>
To: <pgsql-general(at)postgresql(dot)org>
Subject: group by with multiple selects having different where conditions
Date: 2002-04-24 15:30:28
Message-ID: 20020424075200.R53267-100000@crimea.dzhan.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I currently am doing an operation where i take data from two tables and
insert into a third summary table. I'm using the perl dbi to read the
data into my program, work on the data in my program, and then insert back
into the database. it works fine, but I'm investigating whether I can get
better speed by doing all of the functionality in a single SQL statement
instead. For the sake of an example, assume the following sequence/loop
(this isn't really how it's done but seems to convey the desired
functonality):

foreach name (DISTINCT table1.name)

foreach state (DISTINCT table1.state)

x = SELECT sum(table1.count) from table1,table2
WHERE table1.id=table2.id AND table2.type='x'

y = SELECT sum(table1.count) from table1,table2
WHERE table1.id=table2.id AND table2.type='y'

z = SELECT sum(table1.count)

z = z - (x+y)

INSERT into table3 (name,state,x,y,z)

}
}

So, I think that if I were only doing 1 SELECT statement in the inner
loop, I could use an insert select with a group by, something like:

INSERT into table3 (name,state,x)
SELECT table1.name, table1.state, sum(table1.count)
FROM table1,table2 WHERE table1.id=table2.id AND
table2.type='x' GROUP BY (table1.name,table1.state)

Is there a way I can do this type of thing when I have multiple select
statements with different WHERE clauses though? ...something like

INSERT into table (a,b,c,d,e)
select (a,b,c) from table where ... group by (a,b)
select (a,b,d) from table where ... group by (a,b)
select (a,b,e) from table where ... group by (a,b)

subselects? temp tables? Thanks for any help or ideas.
--Ben

Responses

Browse pgsql-general by date

  From Date Subject
Next Message tony 2002-04-24 15:30:38 Re: how does NOT work?
Previous Message Jean-Luc Lachance 2002-04-24 15:27:24 Re: how does NOT work?