Re: Group And Sort After Union

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: cnliou(at)eurosport(dot)com (cnliou)
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Group And Sort After Union
Date: 2002-08-02 13:47:20
Message-ID: 29427.1028296040@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

cnliou(at)eurosport(dot)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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2002-08-02 13:49:53 Re: How to optimize SQL query ?
Previous Message Cédric Dufour (Cogito Ergo Soft) 2002-08-02 13:17:29 Re: How to optimize SQL query ?