按聚合函数分组来计算行数,将计数映射到用户组

时间:2014-03-29 22:22:13

标签: mysql sql group-by aggregate-functions aggregate

对于那些熟悉 Minecraft 的人,我试图在一个SELECT查询中计算每个用户打破的每种类型的块数。我认为这被称为GROUP BY聚合函数。我认为我需要使用多个聚合函数来实现我的最终目标。

到目前为止,我只能:

  • 计算已破坏的每种类型的块数
  • 计算每个用户违反的总块数

我认为我需要使用GROUP BY函数来计算每个块被破坏的次数,然后使用子查询中每个用户的GROUP。


问题伪代码:

  • 选择播放器 block_id 计数(*) action_type 等于 “封锁”
  • 计算块被破坏的次数(通过计算每个 block_id 的出现次数)
  • GROUP by block_id

我尝试过的内容:output

SELECT player, block_id, COUNT(block_id) FROM prism_actions WHERE action_type = 'block-break' GROUP BY block_id;

同时([输出])2

  • 此功能似乎计算出适当的值。

SELECT player, block_id, count(*) as count from prism_actions where action_type = 'block-break' group by block_id,player order by block_id;


(prism_actions)

Field Type id int(11) unsigned action_time timestamp action_type varchar(20) player varchar(16) world varchar(255) x int(11) y smallint(5) z int(11) block_id mediumint(5) block_subid mediumint(5) old_block_id mediumint(5) old_block_subid mediumint(5) data varchar(255)


我已经执行了一个类似的GROUP BY聚合查询来计算每个玩家的#(死亡|杀死|阻止放置的块)

  • 此查询按预期工作,但只需要一个GROUP BY函数
  • 根据 action_type 计算每个操作的SUM(即玩家杀死,玩家死亡,阻止,阻止地点
  • 输出如下:

lower(player) kills deaths blocks_broken blocks_placed joey 41 4 4911 2678 kate 74 1 4944 4762 bill 129 4 2782 1271 jack 335 12 12403 5886

代码: SELECT LOWER(player), SUM(CASE WHEN action_type = 'player-kill' THEN 1 ELSE 0 END) AS kills, SUM(CASE WHEN action_type = 'player-death' THEN 1 ELSE 0 END) AS deaths, SUM(CASE WHEN action_type = 'block-break' THEN 1 ELSE 0 END) AS blocks_broken, SUM(CASE WHEN action_type = 'block-place' THEN 1 ELSE 0 END) AS blocks_placed FROM prism_actions WHERE action_type IN ('block-break', 'block-place', 'player-kill', 'player-death') AND LOWER(player) NOT IN ('creeper', 'fireball', 'environment') GROUP BY player;


提前谢谢。

我意识到我的代表在StackOverflow上很低,但我希望这不会影响你的答案,或导致任何形式的歧视。

1 个答案:

答案 0 :(得分:0)

在此处使用ROLLUP修饰符来获取您所追求的内容。

SELECT player, block_id, count(*) as count 
from prism_actions 
where action_type = 'block-break' 
group by player, block_id WITH ROLLUP
order by block_id;

这将提供类似于

的记录集
Player | Block | Count
NULL     NULL    100
1        NULL    100
1        1       75
1        2       25

其中player = 1且block = NULL是总计,低于此是按块类型计数。