按名称,时间和sum_average对句点进行分组

时间:2017-07-19 17:35:03

标签: mysql sql

我有一个名为Periods的表,我需要用它的数据创建以下结构。

{
  name: place_type
  data: [[hour], avg(attendance)]
}

平均=出勤总数/期数

示例:

{
  name: "Swimming Room", 
  data: [["06:00", 10], ["07:00", 16], ["08:00", 28]]
}

基本上我需要对place_type,小时和出勤率进行分组。

我写了这个查询,但我不知道如何计算平均值

SELECT 
    SUM(`periods`.`attendance`)/COUNT(*) AS sum_attendance,
    place_types.name AS place_types_name,
    LPAD(HOUR(`periods`.`start_at`), 2, 0) AS rounded_hour

    FROM `periods` LEFT OUTER JOIN `place_types` 
        ON `place_types`.`id` = `periods`.`place_type_id` 
        WHERE `periods`.`location_id` = 131 
            AND (`periods`.`start_at` BETWEEN '2017-06-29 06:00:00' AND '2017-06-29 23:00:00')
        GROUP BY place_types.name, rounded_hour

当前结果

sum_attendance  place_types_name    rounded_hour
1762            swim                14
1587            box                 14

预期结果是

sum_attendance  place_types_name    rounded_hour
avg         swim                0
avg         swim                1
avg         swim                2
avg         swim                3
avg         swim                4
avg         swim                5
avg         swim                6
avg         swim                7

...............     平均游泳23

avg         box                 1
........
avg         box                 23

更新1

在分隔符中添加COUNT(*)计算正确的平均值

SUM(`periods`.`attendance`)/COUNT(*) AS average_attendance

它产生以下结果:

sum_attendance  place_types_name    rounded_hour
160.1818        cardio              14
158.7000        esteira             14
149.8000        shape               14

但它仍然无法计算每个小时。

1 个答案:

答案 0 :(得分:1)

periods中有数据时,此查询应该可以获得每小时的平均值:

SELECT AVG(p.`attendance`) AS sum_attendance,
       pt.name AS place_types_name,
       LPAD(HOUR(p.`start_at`), 2, 0) AS rounded_hour
FROM `periods` p LEFT OUTER JOIN
     `place_types` pt
      ON pt.`id` = p.`place_type_id` 
WHERE p.`location_id` = 131 AND
      p`.`start_at` BETWEEN '2017-06-29 06:00:00' AND '2017-06-29 23:00:00'
GROUP BY pt.name, rounded_hour;

如果您没有数据,则小时不会显示在结果集中。