我有兩張表:城市和州。州有州代碼和全名列。Cities 包含人口、州代碼和城市名稱的列。我的目標是在每個人口最多的州創建一個城市表。
這是我的解決方案,似乎在測驗中有效,但有人告訴我使用 max() 是不確定的,我應該使用視窗函式。
SELECT
s.name,
c.name,
max(c.population)
FROM cities AS c
LEFT JOIN states AS s
ON c.state_code = s.code
GROUP BY s.name
ORDER BY s.name;
在這里使用 max 有什么問題,什么時候會給出不正確的結果?
uj5u.com熱心網友回復:
在大多數資料庫中,您的查詢甚至不會運行,因為您選擇了非聚合列c.name,而沒有在GROUP BY子句中使用它。
對于 MySql,如果ONLY_FULL_GROUP_BY模式被禁用,代碼會運行,但它仍然會回傳錯誤的結果,因為查詢會從每個州的所有城市中選擇一個隨機城市名稱。
請參閱演示。
對于 SQLite,您的查詢是正確的!
SQLite 的裸列功能,確保您在結果中獲得的城市名稱是人口最多的城市名稱。
這是非標準的,但已記錄在案。
這里唯一的問題是,如果有 2 個或更多城市的最大人口數相同,則結果中只會得到其中一個。
請參閱演示。
uj5u.com熱心網友回復:
您可以在每個州中找到人口最多的城市,并在子查詢中使用它并將其與表連接起來。
詢問
select s.name as state, c.name as city, c.population
from states s
join cities c
on c.state_code = s.code
join (
select state_code, max(population) as max_pop
from cities
group by state_code
) as p
on p.state_code = c.state_code
and p.max_pop = c.population;
uj5u.com熱心網友回復:
create table states(code varchar(50),name varchar(50));
create table cities(code varchar(50),name varchar(50),population int, state_code varchar(50));
insert into states values('s01','state1');
insert into cities values('c01','city1',100,'s01');
insert into cities values('c02','city2',10,'s01');
詢問:
with cte as
(
SELECT
s.name state_name,
c.name city_name,
c.population,
row_number()over(partition by s.name order by c.population desc)rn
FROM cities AS c
LEFT JOIN states AS s
ON c.state_code = s.code
)
select state_name, city_name, population from cte where rn=1
輸出:
| 州名 | 城市名 | 人口 |
|---|---|---|
| 狀態1 | 城市1 | 100 |
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/490802.html
