mysql> select user_id as 用户id,count(id) as 下单数量 from t_order group by 用户id; +----------+--------------+ | 用户id | 下单数量 | +----------+--------------+ | 1001 | 3 | | 1002 | 4 | | 1003 | 2 | +----------+--------------+ 3 rows in set (0.00 sec)
多个字段分组
例子2:下面的例子展示了,如何进行多个字段的分组。
查询每个用户每年的下单数量,并且输出用户id、年份和下单数量,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12
mysql> select user_id as 用户id,create_year as 年份,count(id) as 下单数量 from t_order group by 用户id,年份; +----------+--------+--------------+ | 用户id | 年份 | 下单数量 | +----------+--------+--------------+ | 1001 | 2018 | 2 | | 1001 | 2019 | 1 | | 1002 | 2018 | 3 | | 1002 | 2019 | 1 | | 1003 | 2018 | 1 | | 1003 | 2019 | 1 | +----------+--------+--------------+ 6 rows in set (0.00 sec)
分组前筛选数据
有时候我们需要在分组前对数据进行筛选,此时就需要使用到where关键字。
例子3:下面的例子展示了,如何在分组前来筛选数据。
查询2018年每个用户的下单数量,并且输出用户id和下单数量,如下所示:
1 2 3 4 5 6 7 8 9
mysql> select user_id as 用户id,count(id) as 下单数量 from t_order where create_year=2018 group by 用户id; +----------+--------------+ | 用户id | 下单数量 | +----------+--------------+ | 1001 | 2 | | 1002 | 3 | | 1003 | 1 | +----------+--------------+ 3 rows in set (0.00 sec)
分组后筛选数据
我们除了可以在分组前筛选数据,其实还可以在分组后筛选数据,此时就需要使用到having关键字。
例子4:下面的例子展示了,如何在分组后来筛选数据。
查询2018年订单数量大于1的用户信息,并且输出用户id和下单数量,那么此时SQL语句如下所示:
1 2 3 4 5 6 7 8
mysql> select user_id as 用户id,count(id) as 下单数量 from t_order where create_year =2018 group by 用户id having 下单数量 >1; +----------+--------------+ | 用户id | 下单数量 | +----------+--------------+ | 1001 | 2 | | 1002 | 3 | +----------+--------------+ 2 rows in set (0.00 sec)
mysql> select user_id as 用户id,max(price) as 最大金额 from t_order group by 用户id order by 最大金额 desc; +----------+--------------+ | 用户id | 最大金额 | +----------+--------------+ | 1001 | 88.88 | | 1003 | 66.66 | | 1002 | 44.44 | +----------+--------------+ 3 rows in set (0.00 sec)
mysql> select user_id as 用户id,count(id) as 下单数量 from t_order where create_year=2018 group by 用户id having 下单数量 >1 order by 下单数量 desc limit 1; +----------+--------------+ | 用户id | 下单数量 | +----------+--------------+ | 1002 | 3 | +----------+--------------+ 1 row in set (0.00 sec)
mysql> select user_id as 用户id,max(price) as 最大金额,create_year as 下单年份 from t_order group by 用户id; ERROR 1055 (42000): Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'envybook.t_order.create_year' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
mysql> select t1.user_id as 用户id, t1.price as 最大金额,t1.create_year as 下单年份 -> from t_order as t1, -> (select t.user_id as tuid,max(t.price) as p -> from t_order as t -> group by t.user_id) as t2 -> where t1.user_id = t2.tuid and t1.price =t2.p; +----------+--------------+--------------+ | 用户id | 最大金额 | 下单年份 | +----------+--------------+--------------+ | 1001 | 88.88 | 2018 | | 1002 | 44.44 | 2019 | | 1003 | 66.66 | 2019 | +----------+--------------+--------------+ 3 rows in set (0.00 sec)