mysql> select * from staff;
+——+——–+——–+
| id | name | deptid |
+——+——–+——–+
| 1 | yamada | 1 |
| 2 | honda | 4 |
| 3 | kudou | 6 |
| 4 | nishi | 1 |
| 5 | tagawa | 3 |
+——+——–+——–+
5 rows in set (0.00 sec)
mysql> select deptid, sum(id) from staff grop by deptid;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘by deptid’ at line 1
mysql> select deptid, sum(id) from staff group by deptid;
+——–+———+
| deptid | sum(id) |
+——–+———+
| 1 | 5 |
| 3 | 5 |
| 4 | 2 |
| 6 | 3 |
+——–+———+
4 rows in set (0.02 sec)
なるほど、あるカラムの値に重複がある場合に、group byでまとめて計算できるのね。
なんとなくわかってきた。