157 words
1 minute
WHERE & HAVING
2025-06-29

https://sqlzoo.net/wiki/SUM_and_COUNT

🎯 WHERE和HAVING根本区别总结#

WHEREHAVING
作用对象原始数据行(分组前)分组后的聚合结果(分组后)
执行时机在 GROUP BY 之前执行在 GROUP BY 之后执行
可使用列名、普通函数聚合函数(SUM, COUNT, AVG 等)
不可用聚合函数原始列名(除非在 GROUP BY 中)
类比筛选原材料筛选成品

经典例题#

  • Counting big countries in each continent#

For each continent show the continent and number of countries with populations of at least 10 million.

SELECT continent, COUNT(name)
FROM world
WHERE population >= 10000000
GROUP BY continent
continentCOUNT(name)
Africa29
Asia26
Caribbean2
Eurasia1
Europe14
North America4
Oceania1
South America8
  • Counting big continents#

List the continents that have a total population of at least 100 million.

SELECT continent
FROM world
GROUP BY continent
HAVING SUM(population) >= 100000000
continent
Africa
Asia
Eurasia
Europe
North America
South America
WHERE & HAVING
https://fishlet.top/posts/sql_learning_note_4/
Author
Ember
Published at
2025-06-29
License
CC BY-NC-SA 4.0