Skip to content

Instantly share code, notes, and snippets.

@JohnArchieMckown
Last active August 29, 2015 14:05
Show Gist options
  • Save JohnArchieMckown/d4b7aedea8db713df80f to your computer and use it in GitHub Desktop.
Save JohnArchieMckown/d4b7aedea8db713df80f to your computer and use it in GitHub Desktop.
Example PostgreSQL CTE
CREATE TABLE t (country text, city text, ... other fields);
--
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;
--
WITH CountryCount AS (
SELECT COUNT(country) as countcountry,
country
FROM t
GROUP BY country
),
CityCount AS (
SELECT COUNT(city) as "CityCount",
city,
country
FROM t
GROUP BY country, city
)
SELECT b.countcountry AS "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
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment