Last active
August 29, 2015 14:05
-
-
Save JohnArchieMckown/d4b7aedea8db713df80f to your computer and use it in GitHub Desktop.
Example PostgreSQL CTE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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