MySQL多个COUNTs

时间:2013-06-06 21:10:40

标签: mysql

我有一张这样的表:

小提琴:http://sqlfiddle.com/#!2/44d9e/14

CREATE TABLE IF NOT EXISTS `mytable` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(20) NOT NULL,
  `money_earned` int(20) NOT NULL,
  PRIMARY KEY (`id`)
) ;

INSERT INTO mytable (user_id,money_earned) VALUES ("111","10");
INSERT INTO mytable (user_id,money_earned) VALUES ("111","6");
INSERT INTO mytable (user_id,money_earned) VALUES ("111","40");
INSERT INTO mytable (user_id,money_earned) VALUES ("222","45");
INSERT INTO mytable (user_id,money_earned) VALUES ("222","1");
INSERT INTO mytable (user_id,money_earned) VALUES ("333","5");
INSERT INTO mytable (user_id,money_earned) VALUES ("333","19");

我需要知道表格有多少行,有多少不同的用户,以及每个用户获得的次数。

我需要这个结果:

TOTAL_ROWS: 7
TOTAL_INDIVIDUAL_USERS: 3

USER_ID USER_TIMES  
111     3       
222     2       
333     2       

2 个答案:

答案 0 :(得分:2)

你的问题是你想要的总数吗?如果是这样,那么您可以使用rollup

来获取此信息
SELECT coalesce(cast(user_id as char(20)), 'TOTAL USER_TIMES'),
      COUNT(*) as times
FROM mytable
GROUP BY user_id with rollup;

您可以使用此技巧在单独的列中获取用户计数:

SELECT coalesce(cast(user_id as char(20)), 'TOTAL USER_TIMES'),
      COUNT(*) as times, count(distinct user_id) as UserCount
FROM mytable
GROUP BY user_id with rollup;

您意识到SQL查询只返回一个值表。您要求非常具体的格式,通常在应用程序级别更好。也就是说,你可以用这样的东西接近你想要的东西:

select user, times
from ((SELECT 3 as ord, cast(user_id as char(20)) as user, COUNT(*) as times
       FROM mytable
       GROUP BY user_id
      )
      union all
      (select 1, 'Total User Count', count(*)
       from mytable
      )
      union all
      (select 2, 'Total Users', count(distinct user_id)
       from mytable
      )
     ) t
order by ord;

答案 1 :(得分:1)

我认为这可能是一个错字,无论如何你想要总结你的COUNT()times,只需用money_earned替换

SELECT user_id, 
COUNT(*) AS 'times', 
SUM(money_earned) AS 'sum_money'
FROM mytable GROUP BY user_id;

SQL Fiddle