得到一个计数的总和()(*)

时间:2014-07-16 20:06:29

标签: mysql sql

我有一个MySQL表:

  • id(int primary)
  • 用户名(varchar)
  • action(varchar)可以是

每次用户完成某些操作时,我都会插入一条记录。我想用一个SQL语句检索用户数量和他们已完成的操作数量。我想要总结一下有多少用户有0个动作,1个动作,2个动作等...我的理由是按用户名分组以获取每个用户有多少动作,然后对那些具有相同动作数的动作求和。 / p>

SELECT count(*), SUM(count(*)) 
from actions 
group by username 
order by SUM(count(*)) desc

这当然不起作用,但或多或​​少地说我想做什么。这可能吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

select numactions, count(*), min(username), max(username)
from (select username, count(*) as numactions
      from actions
      group by username
     ) a
group by numactions
order by numactions;

答案 1 :(得分:2)

  

我想要总结一下有多少用户有0个动作,1个动作,2个动作等......

SELECT nbOfActions, COUNT(1) nbOfUsers
FROM
    (SELECT COUNT(1) nbOfActions, username 
     FROM actions
    GROUP BY username) x
GROUP BY nbOfActions

如果需要,您可以将ORDER BY添加到外部查询:

ORDER BY COUNT(1) DESC