筛选分组数据

SQL 中级

Jasmin Ludolf

Data Science Content Developer, DataCamp

HAVING

SELECT 
       release_year,
       COUNT(title) AS title_count
FROM films
GROUP BY release_year
WHERE COUNT(title) > 10;
在 "WHERE" 附近的语法错误
第 4 行: WHERE COUNT(title) > 10;
        ^
SELECT 
       release_year,
       COUNT(title) AS title_count
FROM films
GROUP BY release_year
HAVING COUNT(title) > 10;
|release_year|title_count|
|------------|-----------|
|1988        |31         |
|null        |42         |
|2008        |225        |
...
SQL 中级

执行顺序

-- Written code:

SELECT certification, COUNT(title) AS title_count FROM films WHERE certification IN ('G', 'PG', 'PG-13') GROUP BY certification HAVING COUNT(title) > 500 ORDER BY title_count DESC LIMIT 3;
-- Order of execution:

SELECT certification, COUNT(title) AS title_count
FROM films
WHERE certification IN ('G', 'PG', 'PG-13')
GROUP BY certification
HAVING COUNT(title) > 500
ORDER BY title_count DESC
LIMIT 3;
SQL 中级

HAVING 与 WHERE

  • WHERE 过滤行,HAVING 过滤分组
  • 2000 年上映了哪些电影?
SELECT title
FROM films
WHERE release_year = 2000;
|title         |
|--------------|
|102 Dalmatians|
|28 Days       |
...
  • 哪些年份的平均片长超过两小时?
SQL 中级

HAVING 与 WHERE

  • 哪些年份的平均片长超过两小时?
SELECT release_year
FROM films

GROUP BY release_year
HAVING AVG(duration) > 120;
|release_year|
|------------|
|1954        |
|1959        |
...
SQL 中级

Let's practice!

SQL 中级

Preparing Video For Download...