1

我有一个包含每个用户消息的表格:

users
----------------
user_id messages
----------------
  725       0
   30       0
 1436       1
10454       4
    .       .
    .       .
 1507      901

该表包含 74,500 个用户。该表按ASC消息数排序。我现在想计算每百分位数的推文数量,所以:

SELECT SUM(messages) FROM users LIMIT     0, 745;
SELECT SUM(messages) FROM users LIMIT   745, 745;
SELECT SUM(messages) FROM users LIMIT  1490, 745;
.
.
SELECT SUM(messages) FROM users LIMIT 73755, 745;

这个我可以,没问题。我可以编写一个脚本来触发对数据库的查询。但我想知道,难道不能让 MySQL 输出每个用户组的消息总数吗?所以输出会是这样的

group  users         total_messages
-----------------------------------
  1       0 - 745     451
  2     745 - 1490   5627
  .      .      .      .
  .      .      .      .
100   73755 - 74500  2654
4

2 回答 2

1

像这样的东西?

SELECT grp + 1                                       AS `group`,
       CONCAT(grp*grpsize, ' - ', (grp+1)*grpsize-1) AS users,
       SUM(messages)                                 AS total_messages
FROM (
  SELECT   @i:=@i+1, @i DIV grpsize AS grp, grpsize, messages
  FROM     users, (SELECT COUNT(*) / 100 AS grpsize, @i:=0 FROM users) t
  ORDER BY messages
) t
GROUP BY grp
于 2012-07-25T13:04:20.513 回答
1

试试这个:

select group_id,concat(MIN(user_id) ,'-',MAX(user_id)) as users,
SUM(messages) as messages  
from
  (SELECT ceil(@rownum:= @rownum+1/745 ) AS group_id,user_id,messages
  FROM users, (SELECT @rownum:=0) r
  order by user_id)a
  group by group_id

如果您还希望显示组范围,您可以这样做

select group_id,concat(MIN(rownum) ,'-',MAX(rownum)) as groups,
concat(MIN(user_id) ,'-',MAX(user_id)) as users,
SUM(messages) as messages
from
  (SELECT ceil(@rownum:= @rownum+1/745 ) AS group_id,@slno:= @slno+1 
  as rownum,user_id,messages
  FROM users, (SELECT @rownum:=0)k,(select @slno:=0) r
  order by user_id)a
  group by group_id
于 2012-07-25T13:23:28.330 回答