group by with multiple selects having different where conditions - Mailing list pgsql-general

From Benjamin Franks
Subject group by with multiple selects having different where conditions
Date
Msg-id 20020424075200.R53267-100000@crimea.dzhan.com
Whole thread Raw
Responses Re: group by with multiple selects having different where conditions  (Masaru Sugawara <rk73@sea.plala.or.jp>)
List 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


pgsql-general by date:

Previous
From: Jean-Luc Lachance
Date:
Subject: Re: how does NOT work?
Next
From: "ARP"
Date:
Subject: Re: Bug or syntax error in my update query with a FROM statement ?