Filtern gruppierter Daten

SQL für Fortgeschrittene

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;
syntax error at or near "WHERE"
LINE 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 für Fortgeschrittene

Reihenfolge der Ausführung

-- 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 für Fortgeschrittene

HAVING vs. WHERE

  • WHERE filtert einzelne Datensätze, HAVING filtert gruppierte Datensätze
  • Welche Filme wurden im Jahr 2000 veröffentlicht?
SELECT title
FROM films
WHERE release_year = 2000;
|title         |
|--------------|
|102 Dalmatians|
|28 Days       |
...
  • In welchen Jahren lag die durchschnittliche Filmdauer bei über zwei Stunden?
SQL für Fortgeschrittene

HAVING vs. WHERE

  • In welchen Jahren lag die durchschnittliche Filmdauer bei über zwei Stunden?
SELECT release_year
FROM films

GROUP BY release_year
HAVING AVG(duration) > 120;
|release_year|
|------------|
|1954        |
|1959        |
...
SQL für Fortgeschrittene

Lass uns üben!

SQL für Fortgeschrittene

Preparing Video For Download...