Groepsresultaten beperken

Introductie tot Oracle SQL

Hadrien Lacroix

Content Developer

Terug naar ons voorbeeld

SELECT Composer, AVG(Milliseconds)
FROM Track
WHERE UnitPrice = 0.99
GROUP BY Composer
| Composer        | AVG(Milliseconds) |
|-----------------|-------------------|
| Antonio Vivaldi | 199,086.0         |
| Pearl Jam       | 94,197.0          |
| Jimmy Page      | 474,888.3         |
| Carlos Santana  | 499,234.3         |
| ...             | ...               |

En filteren na groeperen?

Introductie tot Oracle SQL

Beperkingen van WHERE

  • WHERE kan geen groepen filteren
    • Groepsfuncties kun je niet in WHERE-clausules gebruiken
Introductie tot Oracle SQL

Voorbeeld: beperkingen van WHERE

SELECT Composer, AVG(Milliseconds)
FROM Track
GROUP BY Composer
WHERE AVG(Milliseconds) > 200000
syntax error at or near "WHERE"
LINE 4: WHERE AVG(Milliseconds) > 200000
        ^
Introductie tot Oracle SQL

HAVING

SELECT Composer, AVG(Milliseconds)
FROM Track
GROUP BY Composer
HAVING AVG(Milliseconds) > 200000
| composer    | avg    |
|-------------|--------|
| George Duke | 274155 |
| Miles Davis | 391146 |
| R. Carless  | 251585 |
| ...         | ...    |
Introductie tot Oracle SQL

Groepsresultaten beperken met HAVING

Stroomschema van de HAVING-clausule

Introductie tot Oracle SQL

HAVING

SELECT Composer, MAX(Milliseconds)
FROM Track
GROUP BY Composer
HAVING MAX(Milliseconds) > 200000
| composer    | max    |
|-------------|--------|
| George Duke | 274155 |
| Miles Davis | 907520 |
| R. Carless  | 251585 |
| ...         | ...    |

Introductie tot Oracle SQL

Nog een voorbeeld

SELECT Composer, SUM(UnitPrice)
FROM Track
WHERE GenreId = 1
GROUP BY Composer
HAVING COUNT(*) > 4
| composer      | sum  |
|---------------|------|
| AC/DC         | 7.92 |
| Chris Cornell | 9.90 |
| Eddie Vedder  | 8.91 |
| ...           | ...  |
Introductie tot Oracle SQL

Richtlijnen

  • Je kunt verschillende groepsfuncties gebruiken in SELECT en HAVING

  • HAVING bevat altijd een groepsfunctie

Volgorde van uitvoering:

  1. Rijen worden gefilterd met WHERE en gegroepeerd met GROUP BY
  2. Groepsfunctie toegepast op de groepen
  3. De groepen worden gefilterd met HAVING en dan getoond
Introductie tot Oracle SQL

Laten we oefenen!

Introductie tot Oracle SQL

Preparing Video For Download...