SQL ile Raporlama
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 |
+-----+--------+--------------+

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

Ara Tablo
+-----+------+--------------+---------+
| id | year | matches_won | points |
|-----|------|--------------|---------|
| 1 | 2016 | 5 | 52 | <--
| 1 | 2017 | 2 | 52 | <-- SUM(points) = 52 x 3 = 156
| 1 | 2018 | 3 | 52 | <--
+-----+------+--------------+---------+
1. Toplamaları kaldırın
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. JOIN ifadesine alan ekleyin
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. JOIN ifadesine alan ekleyin
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. Alt sorgu ile özetleyin
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;
Orijinal tablodaki değer:
SELECT SUM(points) AS total_points
FROM points;
total_points = 52
Sorgudaki değer:
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

SQL ile Raporlama