group by查询旨在把某字段中相同的记录合并成一列,查询结果可受count(),sum()等统计函数影响
如下表
id | totalclick | validclick |
1 | 3 | 1 |
2 | 3 | 1 |
3 | 5 | 2 |
4 | 2 | 1 |
5 | 3 | 1 |
6 | 5 | 2 |
以validclick为分组,统计每个分组的记录数,和每个分组的totalclick总和
SELECT count(`id`),sum(`totalclick`), validclick FROM diary_log GROUP BY validclick;
结果:
count(`id`) | sum(`totalclick`) | validclick |
4 | 11 | 1 |
2 | 10 | 2 |
配合if,可以模拟count()统计每个分组的记录数
SELECT count(`id`), sum(if(validclick = 1,1,0)) validclick_1,sum(if(validclick = 2,1,0)) validclick_2,validclick FROM diary_log GROUP BY validclick;
结果:
count(`id`) | validclick_1 | validclick_2 | validclick |
4 | 4 | 0 | 1 |
2 | 0 | 2 | 2 |