如何从小时mysql存储日期值的表中获取每日总计的平均值和标准偏差?

如何从小时mysql存储日期值的表中获取每日总计的平均值和标准偏差?

问题描述:

I a do have a table that stores a total count of error by hour, by day.

I need to calculate the average of the total number of errors by day, I was trying something like this:

SELECT 
  error_code, 
  AVG(total) as avg, 
  STDDEV_SAMP(total) as std
FROM 
  error_monitoring 
WHERE
  date_sub(curdate(), interval 30 day) <= date 
GROUP BY
  error_code 

But the result of the query is based on the hourly values I have in the table and no the daily totals.

The table in database shows as follow:

id | error_code | total | average | standard_deviation | date 
1  | W0334      | 2131  | 81      | 163.349            | 2016-12-20 23:00:00
2  | W0096      | 910   | 45      | 132.915            | 2016-12-20 15:00:00
3  | W0334      | 120   | 81      | 163.349            | 2016-12-20 08:00:00

So, how I can calculate this based on daily totals?

If you want the "average by day", you can calculate the total and then divide by the number of days:

SELECT error_code, SUM(total) / COUNT(DISTINCT date(date)) as avg
FROM error_monitoring
WHERE date_sub(curdate(), interval 30 day) <= date
GROUP BY error_code 

Your code also includes STDDEV_SAMP(). If you also want that calculation, then you would need to use a subquery, aggregating by day. Assuming that all error codes are available on each day:

SELECT error_code, AVG(day_total), STDDEV_SAMP(day_total)
FROM (SELECT error_code, date(date) as dte, SUM(total) as day_total 
      FROM error_monitoring
      WHERE date_sub(curdate(), interval 30 day) <= date
      GROUP BY error_code, date(date)
     ) em
GROUP BY error_code;