Eseguire query su un database PostgreSQL in Java
Miller Trujillo
Staff Software Engineer
Riassumi più righe in un unico risultato
COUNT: numero di righe
SUM: totale dei valori numericiAVG: media dei valori numericiSELECT COUNT(*) AS total_books,
AVG(publication_year) AS avg_year
FROM books;
|total_books |avg_year |
|--------------|---------|
|14 |1999.14 |
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 |
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 |
WHERE filtra le righe prima del raggruppamentoHAVING filtra i gruppi dopo l'aggregazioneSELECT publication_year, COUNT(*) AS books_written
FROM books b
GROUP BY publication_year
HAVING COUNT(*) > 2;
| publication_year | books_written |
| ---------------- | ------------- |
| 2018 | 3 |
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 libritry (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