MySQL如何对GROUP BY计数列?

时间:2019-07-10 03:29:07

标签: mysql sql select group-by count

我有两个表用户,订单

每个表的下面一列

users(table)
id

orders(table)
user_id

我如何获得订单数量为1,2,3,4 .... n的用户数量?

喜欢吗?

users count    |   order count
999            |   1
100            |   2
 80            |   3
 70            |   4
 60            |   5
 50            |   6

到目前为止,我一直在尝试

SELECT cnt.uid as u_cnt, cnt.ocnt as or_cnt
FROM (
  SELECT u.id as uid, COUNT(o.id) as o_cnt
  FROM users as u
  INNER JOIN orders o on u.id = o.user_id
) as cnt;
GROUP BY or_cnt

但是我只得到1个u_cnt并求和or_cnt

2 个答案:

答案 0 :(得分:2)

此处需要两个级别的group by子句:首先,您需要按用户分组并计算每个用户所拥有的订单数。然后,您需要获取该结果,将订单数量分组并计算有多少用户拥有该订单数量。

最简单的方法可能是使用子查询,其中内部查询和外部查询都有一个group by子句:

SELECT cnt.ocnt as or_cnt, COUNT(*) as user_count
FROM (
  SELECT u.id as uid, COUNT(o.id) as o_cnt
  FROM users as u
  INNER JOIN orders o on u.id = o.user_id
  GROUP BY u.id -- This was missing in your original query
) as cnt
GROUP BY or_cnt

答案 1 :(得分:1)

您可以使用两个级别的聚合。更重要的是,您不需要JOIN。您需要的所有信息都在orders中:

SELECT o_cnt, COUNT(*) as user_count
FROM (SELECT o.user_id, COUNT(*) as o_cnt
      FROM orders o
      GROUP BY o.user_id 
     ) u
GROUP BY o_cnt
ORDER BY o_cnt;