From: | John McKown <john(dot)archie(dot)mckown(at)gmail(dot)com> |
---|---|
To: | PostgreSQL General <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: select top_countries and for each country, select top_cities in that country, in 1 query |
Date: | 2014-08-28 12:35:43 |
Message-ID: | CAAJSdjg26soFO1ZcphS7n3J74s=c7maoJ_tR_sSifuD=3EV3YQ@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Mon, Aug 18, 2014 at 10:52 AM, John McKown
<john(dot)archie(dot)mckown(at)gmail(dot)com> wrote:
>
> SELECT avg(b.countcountry)::int as "CountryCount", b.country, a.city,
> count(a.city) as "CityCount"
> FROM t AS a
> INNER JOIN
> (SELECT COUNT(country) AS countcountry, country FROM t GROUP BY country) AS
> b
> ON a.country = b.country
> GROUP BY b.country, a.city
> ORDER BY 1 DESC,4 DESC;
>
I am curious that nobody pointed out that the above might work but is
really poor code. Given that, I wonder what the people here think of
the following code. It seems "better" to me, even if it is more wordy.
WITH CountryCount AS (
SELECT COUNT(country) as "countryCount",
country
FROM t
GROUP BY country
),
CityCount AS (
SELECT COUNT(city) as "cityCount",
city,
country
FROM t
GROUP BY country, city
)
SELECT b."countryCount",
b.country,
a.city,
a."cityCount"
FROM CityCount as a
INNER JOIN
CountryCount AS b
ON a.country = b.country
ORDER BY b.countcountry DESC,
a.city DESC
--
There is nothing more pleasant than traveling and meeting new people!
Genghis Khan
Maranatha! <><
John McKown
From | Date | Subject | |
---|---|---|---|
Next Message | Dorian Hoxha | 2014-08-28 13:26:35 | Re: select top_countries and for each country, select top_cities in that country, in 1 query |
Previous Message | Maeldron T. | 2014-08-28 12:20:51 | Failback to old master |