Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions SQL Deep Dive/Window Functions/exercises.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
* Database: World
* Table: Country
*/

SELECT *
FROM country;

SELECT DISTINCT continent, SUM(population)
OVER w1 AS "Continent Population"
FROM country
WINDOW w1 AS (PARTITION BY continent);
/*
* To the previous query add on the ability to calculate the percentage of the world population
* What that means is that you will divide the population of that continent by the total population and multiply by 100 to get a percentage.
Expand All @@ -16,10 +16,18 @@ FROM country;
* Database: World
* Table: Country
*/

SELECT *
FROM country;

SELECT
DISTINCT continent,
SUM(population) OVER w1 as"continent population",
CONCAT(
ROUND(
(
SUM(population::float4) OVER w1 /
SUM(population::float4) OVER()
) * 100
),'%' ) as "% of population"
FROM country
WINDOW w1 AS( PARTITION BY continent );

/*
* Count the number of towns per region
Expand All @@ -28,5 +36,14 @@ FROM country;
* Table: Regions (Join + Window function)
*/

SELECT *
SELECT DISTINCT r.id,
r."name",
COUNT(t.id) OVER(
PARTITION BY r.id
ORDER BY r."name"
) AS "No of towns"
FROM regions as r
JOIN departments as d ON r.code = d.region
JOIN towns as t ON d.code = t.department
ORDER BY r.id;
FROM regions AS r;