MySQL,获取一周中所有天的平均值

时间:2018-07-15 22:59:55

标签: mysql aggregate average

我有一个表,其中包含我所在位置无法使用或有空的每个小时所存储的数据。我当前的查询获取一整天的平均入住率/免费点数:

SELECT AVG(sz.occupied), AVG(sz.free)
FROM `hourly_cache` AS sz
WHERE   sz.time BETWEEN '2017-01-01 00:00:00' AND '2017-01-02 00:00:00'
        AND HOUR(sz.time) BETWEEN 8 AND 22
        AND libID = 0

但是,如果我不仅要在这一天,还要在一周中的其他每一天都想得到平均值,该怎么办?说:我想要本周周一的平均值,再加上周二,周三等。

我该如何遍历每一天,并根据每天是哪一天运行此查询?

我当时正在考虑用PHP进行此操作,但想知道是否有一种方法可以在MySQL中使用?

1 个答案:

答案 0 :(得分:3)

根据业务逻辑以及您希望如何呈现它,可能有太多解决方案。


1)将time字段分配到datetime,然后按date分组:

SELECT AVG(sz.occupied), AVG(sz.free), date, time
FROM `hourly_cache` AS sz
WHERE   
  (sz.date >= '2017-01-01' AND sz.date < '2017-01-07')
  AND HOUR(sz.time) BETWEEN 8 AND 22
  AND libID = 0
GROUP BY date;



2)将时间转换为日期并按日期分组:

SELECT AVG(sz.occupied), AVG(sz.free), DATE(sz.time) as date
FROM `hourly_cache` AS sz
WHERE   
  (sz.time >= '2017-01-01 00:00:00' AND sz.time < '2017-01-07 00:00:00')
  AND HOUR(sz.time) BETWEEN 8 AND 22
  AND libID = 0
GROUP BY date;



3)使用DAYOFWEEK函数

SELECT AVG(sz.occupied), AVG(sz.free), DAYOFWEEK(sz.time) as day_of_week
FROM `hourly_cache` AS sz
WHERE   
  (sz.time >= '2017-01-01 00:00:00' AND sz.time < '2017-01-07 00:00:00')
  AND HOUR(sz.time) BETWEEN 8 AND 22
  AND libID = 0
GROUP BY day_of_week;



4)将day_of_weekweek_num字段添加到hourly_cache表中,在插入或更新时进行设置。

然后像这样查询它:

SELECT AVG(sz.occupied), AVG(sz.free), week_num, day_of_week
FROM `hourly_cache` AS sz
WHERE   
  (sz.time >= '2017-01-01 00:00:00' AND sz.time < '2017-01-07 00:00:00')
  AND HOUR(sz.time) BETWEEN 8 AND 22
  AND libID = 0
GROUP BY week_num, day_of_week;



5)如果您不能更改表结构,则可以创建视图(但是我不确定性能):

CREATE VIEW v_avarage_seats_by_date AS 
  SELECT 
    AVG(sz.occupied) as occupied, 
    AVG(sz.free) as free, 
    DATE(sz.time) as date,
    DAYOFWEEK(sz.time) as day_of_week
  FROM `hourly_cache` AS sz
  WHERE   
    (HOUR(sz.time) BETWEEN 8 AND 22) AND libID = 0
  GROUP BY date;

然后像这样查询它:

SELECT * FROM v_avarage_seats_by_date WHERE date >= '2017-01-01' AND date =< '2017-01-07'