MySQL:如何计算按day_hour分组的分钟行数

时间:2018-04-27 16:43:29

标签: mysql datetime

我的select效果很好,除非每小时的计数相同:

SQLfiddle:http://sqlfiddle.com/#!9/bae01d/32

Player  | Day | Hour | Minutes | % online
player1 |  27 |    0 |      60 |      100
player1 |  27 |    1 |      60 |      100
player1 |  27 |    2 |      60 |      100
player1 |  27 |    3 |      60 |      100
player1 |  27 |    4 |      60 |      100
...

活动表只有在线玩家的分钟条目,离线玩家将丢失。这是连接的来源,存根表包含24行,小时为0-23。

如何重写此查询,以便玩家在线的每小时总分数是正确的总数?

select 
    player, 
    day(datetime) as Day,
    stub.hour,
    hour(datetime) as Hour, 
    count(player) as minutes,
    ((count(player) / 60) * 100) as percent_of_hr
 FROM stub_hours as stub
 LEFT JOIN activity
  on Hour=stub.hour
    GROUP BY date_format( datetime, '%Y%m%d%h' ), Day, Hour, player
    ORDER BY player, datetime desc, Day, hour, minutes desc;

1 个答案:

答案 0 :(得分:1)

我相信这应该是你所需要的:

SELECT
  sh.player,
  sh.day,
  sh.hour,
  act.count_minutes minutes,
  ((act.count_minutes / 60) * 100) AS percent_of_hr
FROM (SELECT
  player,
  MONTH(datetime) amonth,
  DAY(datetime) aday,
  HOUR(datetime) ahour,
  COUNT(*) count_minutes
FROM activity
GROUP BY player,
         MONTH(datetime),
         DAY(datetime),
         HOUR(datetime)) act
RIGHT JOIN (SELECT DISTINCT
  a.player,
  s.hour,
  DAY(a.datetime) day,
  MONTH(a.datetime) month
FROM activity a
CROSS JOIN stub_hours s) sh
  ON act.ahour = sh.hour
  AND act.player = sh.player
  AND act.aday = sh.day
  AND act.amonth = sh.month
ORDER BY sh.player, sh.day, sh.hour;

http://sqlfiddle.com/#!9/84fc1d/70

如果您需要不同的输出,请告诉我。