1

我有一张这样的桌子:

小提琴: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       
4

2 回答 2

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;
于 2013-06-06T21:23:16.507 回答
1

无论如何,我认为这可能是一个错字,您试图对您的 COUNT() 求和times,只需替换为money_earned

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

SQL小提琴

于 2013-06-06T21:14:05.120 回答