报告中的重复

SQL 报表制作

Tyler Pernes

Learning & Development Consultant

重复的原因是什么?

SQL 报表制作

重复的原因是什么?

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;
SQL 报表制作

重复的原因是什么?

+-----+--------+--------------+
| id  | points | matches_won  |
|-----|--------|--------------|
| 1   | 156    | 10           |
+-----+--------+--------------+
1 将导致 points 的值变为应有值的三倍,此处为 156。
SQL 报表制作

重复的原因是什么?

中间表
+-----+------+--------------+---------+ 
| id  | year | matches_won  | points  |
|-----|------|--------------|---------|    
| 1   | 2016 | 5            | 52      |
| 1   | 2017 | 2            | 52      |  
| 1   | 2018 | 3            | 52      |
+-----+------+--------------+---------+
SQL 报表制作

重复的原因是什么?

中间表
+-----+------+--------------+---------+ 
| id  | year | matches_won  | points  |
|-----|------|--------------|---------|    
| 1   | 2016 | 5            | 52      | <--
| 1   | 2017 | 2            | 52      | <-- SUM(points) = 52 x 3 = 156
| 1   | 2018 | 3            | 52      | <-- 
+-----+------+--------------+---------+    
SQL 报表制作

修复重复的方法

1. 移除聚合

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           |
+-----+--------+--------------+
SQL 报表制作

修复重复的方法

SQL 报表制作

修复重复的方法

2. 在 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;
SQL 报表制作

修复重复的方法

2. 在 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;
SQL 报表制作

修复重复的方法

SELECT id, SUM(matches_won)
FROM matches
GROUP BY id;
+-----+--------------+
| id  | matches_won  |
|-----|--------------|
| 1   | 10           |
| 2   | 7            |
+-----+--------------+
SQL 报表制作

修复重复的方法

3. 用子查询汇总

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;
SQL 报表制作

修复重复的方法

  1. 移除聚合
  2. 在 JOIN 中增加字段
  3. 用子查询汇总
SQL 报表制作

识别重复

原表中的值:

SELECT SUM(points) AS total_points
FROM points;
total_points = 52

查询中的值:

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 报表制作

本章目标

SQL 报表制作

练习时间!

SQL 报表制作

Preparing Video For Download...