简体   繁体   English

Mysql-计算多少行有一定数量?

[英]Mysql - Count how many rows have a certain number?

I have a query that checks a tables and groups all entries from a user and counts those entries 我有一个查询,该查询检查一个表并将用户的所有条目分组并计数这些条目

  SELECT username, 
         count(userid)  
    FROM orders 
GROUP BY userid

This returns a list of username's and how many orders they have submitted 这将返回用户名列表以及他们已提交的订单数量

username  count(userid)
------------------------
test      1  
test2     1  
test3     3  
test4     3  
test4     3  
test4     3  

What i want the query to do is count how many users have X orders and return that number. 我要查询执行的操作是计算有X个订单的用户数量并返回该数字。

So from the above results users that have 1 order should be 2 and users that have 3 orders should be 4. So on and so forth can this be done? 因此,从以上结果中,拥有1个订单的用户应为2,拥有3个订单的用户应为4。等等,可以这样做吗?

I'd think you could just add something like this around your query: 我认为您可以在查询周围添加如下内容:

SELECT InnerCount, COUNT(*)
FROM
(
    -- your query
    SELECT username, count(userid) AS InnerCount
    FROM orders
    GROUP BY userid
) t1
GROUP BY InnerCount

(Caveat: haven't touched mysql in years) (注意:多年来没有接触过mysql)

Use: 采用:

SELECT COUNT(*)
  FROM (SELECT o.username, 
               COUNT(o.userid) AS cnt
          FROM ORDERS o
      GROUP BY o.userid
        HAVING cnt = ?) x

Replace "?" 替换为“?” with the number you want to see the number of users with that count value. 您想查看具有该计数值的用户数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM