Filtrera gruppresultat

Introduktion till Oracle SQL

Hadrien Lacroix

Content Developer

Tillbaka till exemplet

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         |
| ...             | ...               |

Hur filtrerar vi efter gruppering?

Introduktion till Oracle SQL

WHERE:s begränsningar

  • WHERE kan inte användas för att filtrera grupper
    • Gruppfunktioner kan inte användas i WHERE-satser
Introduktion till Oracle SQL

WHERE:s begränsningar – exempel

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
        ^
Introduktion till 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 |
| ...         | ...    |
Introduktion till Oracle SQL

Filtrera gruppresultat med HAVING

Flöde för HAVING-sats

Introduktion till 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 |
| ...         | ...    |

Introduktion till Oracle SQL

Ett annat exempel

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 |
| ...           | ...  |
Introduktion till Oracle SQL

Riktlinjer

  • Olika gruppfunktioner kan användas i SELECT och HAVING

  • HAVING innehåller alltid en gruppfunktion

Ordning för operationer:

  1. Rader filtreras med WHERE och GROUP BY
  2. Gruppfunktionen tillämpas på grupperna
  3. Grupperna filtreras med HAVING och skrivs ut
Introduktion till Oracle SQL

Nu kör vi en övning!

Introduktion till Oracle SQL

Preparing Video For Download...