Rapporteren in SQL
Tyler Pernes
Learning & Development Consultant


SELECT p.id, SUM(points) AS points, SUM(matches_win) AS matches_won
FROM points AS p
JOIN matches AS m ON p.id = m.id
GROUP BY p.id;

+-----+--------+--------------+
| id | points | matches_won |
|-----|--------|--------------|
| 1 | 156 | 10 |
+-----+--------+--------------+

Tussentabel
+-----+------+--------------+---------+
| id | year | matches_won | points |
|-----|------|--------------|---------|
| 1 | 2016 | 5 | 52 |
| 1 | 2017 | 2 | 52 |
| 1 | 2018 | 3 | 52 |
+-----+------+--------------+---------+

Tussentabel
+-----+------+--------------+---------+
| id | year | matches_won | points |
|-----|------|--------------|---------|
| 1 | 2016 | 5 | 52 | <--
| 1 | 2017 | 2 | 52 | <-- SOM(points) = 52 x 3 = 156
| 1 | 2018 | 3 | 52 | <--
+-----+------+--------------+---------+
1. Verwijder aggregaties
SELECT p.id, points, SUM(matches_won) AS matches_won
FROM points AS p
JOIN matches AS m ON p.id = m.id
GROUP BY p.id, points;
+-----+--------+--------------+
| id | points | matches_won |
|-----|--------|--------------|
| 1 | 52 | 10 |
+-----+--------+--------------+


2. Voeg veld toe aan JOIN
SELECT p.id, SUM(points) AS points, SUM(matches_win) AS matches_won
FROM points AS p
JOIN matches AS m ON p.id = m.id AND p.year = m.year
GROUP BY p.id;

2. Voeg veld toe aan JOIN
SELECT p.id, SUM(points) AS points, SUM(matches_win) AS matches_won
FROM points AS p
JOIN matches AS m ON p.id = m.id AND p.year = m.year
GROUP BY p.id;
SELECT id, SUM(matches_won)
FROM matches
GROUP BY id;
+-----+--------------+
| id | matches_won |
|-----|--------------|
| 1 | 10 |
| 2 | 7 |
+-----+--------------+

3. Rollup met subquery
SELECT p.id, points, matches_won
FROM points AS p
JOIN
(SELECT id, SUM(matches_won) AS matches_won
FROM matches
GROUP BY id) AS m
ON p.id = m.id;
Waarde in originele tabel:
SELECT SUM(points) AS total_points
FROM points;
total_points = 52
Waarde in query:
SELECT SUM(points) AS total_points
FROM
(SELECT p.id, SUM(points) AS points
FROM points AS p
JOIN matches AS m ON p.id = m.id
GROUP BY p.id) AS subquery;
total_points = 156

Rapporteren in SQL