group by 有一个原则
就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面
例:有如下数据库表:
a b
1 abc
1 bcd
1 asdfg
对于查询语句:select a, b from table group by a
所得结果:
a b
abc
1 bcd
asdfg
这显而易见是不正确的
解决办法:
①把 b 也加入 group by 之后
select a, b as amount from table group by a, b
②把右边 3 条语句变成一条,所以需要用到聚合函数:
select a, count(b) as amount from table group by a
a amount
1 3