Aggregazioni e Operazioni di Gruppo

Eseguire query su un database PostgreSQL in Java

Miller Trujillo

Staff Software Engineer

Aggregazioni: COUNT, SUM, AVG

  • Riassumi più righe in un unico risultato

  • COUNT: numero di righe

  • SUM: totale dei valori numerici
  • AVG: media dei valori numerici
SELECT COUNT(*) AS total_books,
       AVG(publication_year) AS avg_year
FROM books;
|total_books   |avg_year |
|--------------|---------|
|14            |1999.14  |
Eseguire query su un database PostgreSQL in Java

GROUP BY per Sintesi

  • Divide le righe in gruppi prima di applicare le aggregazioni
SELECT publication_year, COUNT(*) AS books_written
FROM books
GROUP BY publication_year;
| publication_year | books_written |
| ---------------- | ------------- |
| 2017             | 1             |
| 2003             | 1             |
| 1997             | 1             |
| 2018             | 3             |
| 2014             | 1             |
| 1960             | 1             |
Eseguire query su un database PostgreSQL in Java

GROUP BY con Più Colonne

  • Raggruppa per più colonne per dettagli più precisi
SELECT publication_year, c.name, COUNT(*) AS books_written
FROM books b
LEFT JOIN categories c on c.category_id = b.category_id 
GROUP BY publication_year, c.name;
| publication_year | name             | books_written |
| ---------------- | ---------------- | ------------- |
| 1951             | Fiction          | 1             |
| 1960             | Fiction          | 1             |
| 2018             | Computer Science | 3             |
| 1965             | Science Fiction  | 1             |
| 2010             | Fantasy          | 1             |
| 2003             | Computer Science | 1             |
Eseguire query su un database PostgreSQL in Java

Filtrare Gruppi con HAVING

  • WHERE filtra le righe prima del raggruppamento
  • HAVING filtra i gruppi dopo l'aggregazione
SELECT publication_year, COUNT(*) AS books_written
FROM books b
GROUP BY publication_year
HAVING COUNT(*) > 2;
| publication_year | books_written |
| ---------------- | ------------- |
| 2018             | 3             |
Eseguire query su un database PostgreSQL in Java

Aggregazioni e Gruppi in Java

String query = """SELECT publication_year, COUNT(*) AS books_written FROM books b
    GROUP BY publication_year
    HAVING COUNT(*) > ?;""";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
    pstmt.setInt(1, 2); // filtra anni con più di 2 libri

try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { int year = rs.getInt("publication_year"); int count = rs.getInt("books_written"); } } }
| publication_year | books_written |
| ---------------- | ------------- |
| 2018             | 3             |
Eseguire query su un database PostgreSQL in Java

Facciamo pratica!

Eseguire query su un database PostgreSQL in Java

Preparing Video For Download...