是否有可能让MySQL输出百分位组?

时间:2012-07-25 12:46:00

标签: mysql

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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