From 8dcde72666f6baf9bf9d62b758e78bbd552d9a68 Mon Sep 17 00:00:00 2001 From: AdityaTharunJ Date: Wed, 3 Jun 2026 12:59:17 +0530 Subject: [PATCH] Enhance SQL exercises with population calculations Add queries to calculate continent population and percentage of world population, as well as count towns per region. --- SQL Deep Dive/Window Functions/exercises.sql | 35 +++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/SQL Deep Dive/Window Functions/exercises.sql b/SQL Deep Dive/Window Functions/exercises.sql index 6b3a32c..c92aec9 100644 --- a/SQL Deep Dive/Window Functions/exercises.sql +++ b/SQL Deep Dive/Window Functions/exercises.sql @@ -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. @@ -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 @@ -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;