add batch
remove batch
split batch
comment selection
show hidden batches
hide batch
highlight batch
db<>fiddle
Db2
Firebird
MariaDB
MySQL
Node.js
Oracle
Postgres
SQLite
SQL Server
TimescaleDB
YugabyteDB
Developer-C 11.1
3.0
4.0
10.2
10.3
10.4
10.5
10.6
10.7
10.8
10.9
5.5
5.6
5.7
8.0
18
11g Release 2
18c
21c
23c
8.4
9.3
9.4
9.5
9.6
10
11
12
13
14
15
16
3.8
3.16
3.27
3.39
2012
2014
2016
2017
2017 (Linux)
2019
2019 (Linux)
2022
2.11
2.6
2.8
2.18
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
Sakila
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
no sample DB
AdventureWorks
no sample DB
no sample DB
AdventureWorks
no sample DB
no sample DB
no sample DB
no sample DB
run
markdown
donate
feedback
about
By using db<>fiddle, you agree to license everything you submit by
Creative Commons CC0
.
--Source: Markus Winand of modern-sql.com/ --For each country, what city has the highest population? (where the country has more than one city) --Include the city name as a column. -- A so-called "top-n per group" problem. Two common solutions -- 1) ROW_NUMBER() OVER(PARTITON BY) -- 2) LATERAL (ORDER BY ... FETCH FIRST 1 ROW ONLY) -- lateral approach needs a countries table, thus skipping here -- NOTE: your example data is non-deterministic regarding "biggest" (there is a tie) -- Thus a difference a2 vs a3 or b2 vs b3 is not an error. -- With this approach it would be even easy to list both cities if there is a tie: -- Just replace ROW_NUMBER by RANK and it will list the highest pop city -- along with all other cities that have the same population (ties). with cities (city, country, population) as ( select 'a1', 'a', 1 from dual union all select 'a2', 'a', 3 from dual union all select 'a3', 'a', 3 from dual union all select 'b1', 'b', 1 from dual union all select 'b3', 'b', 3 from dual union all select 'b2', 'b', 3 from dual union all select 'c1', 'c', 1 from dual ) SELECT * FROM (SELECT cities.* , ROW_NUMBER() OVER(PARTITION BY country ORDER BY population DESC) rn , COUNT(*) OVER(PARTITION BY country) ct_cities FROM cities ) t WHERE t.rn = 1 AND t.ct_cities > 1
CITY
COUNTRY
POPULATION
RN
CT_CITIES
a2
a
3
1
3
b2
b
3
1
3