Re: Group And Sort After Union - Mailing list pgsql-sql

From Tom Lane
Subject Re: Group And Sort After Union
Date
Msg-id 29427.1028296040@sss.pgh.pa.us
Whole thread Raw
In response to Group And Sort After Union  (cnliou@eurosport.com (cnliou))
List pgsql-sql
cnliou@eurosport.com (cnliou) writes:
> I want to GROUP BY and ORDER BY on the result of UNION similar to the
> following (wrong) SQL:

> (SELECT c11 AS c1,SUM(c12) AS c2 FROM table1
> UNION
> SELECT c21 AS c1,SUM(c22) AS c2 FROM table2
> )
> GROUP BY c1
> ORDER BY c2;

Correct is

SELECT * FROM
(SELECT c11 AS c1,SUM(c12) AS c2 FROM table1
UNION
SELECT c21 AS c1,SUM(c22) AS c2 FROM table2
) ss
GROUP BY c1
ORDER BY c2;
        regards, tom lane


pgsql-sql by date:

Previous
From: Cédric Dufour (Cogito Ergo Soft)
Date:
Subject: Re: How to optimize SQL query ?
Next
From: Tom Lane
Date:
Subject: Re: How to optimize SQL query ?