Compute average sales per day in MySQL

不羁岁月 提交于 2019-12-12 14:57:38

问题


In my database I have a table with two columns. The first column contains dates and the second is a count variable. I was wondering if it is possible to compute the average counts for each weekday based on the dates and counts. In the following a small example:

Table:

Date         Count
02/01/2005     100
02/02/2005     200
02/03/2005     300
...            ...

Output:

 Days       Average
 Monday       120.5         
 Tuesday      200.2                   
 Wednesday    300.5 

回答1:


You could a series of avg calls on case expression extracting the day's name:

SELECT AVG(CASE DAYOFWEEK(`date`) WHEN 2 THEN `count` ELSE NULL END) AS Monday,
       AVG(CASE DAYOFWEEK(`date`) WHEN 3 THEN `count` ELSE NULL END) AS Tuesday,
       AVG(CASE DAYOFWEEK(`date`) WHEN 4 THEN `count` ELSE NULL END) AS Wednesday,
       AVG(CASE DAYOFWEEK(`date`) WHEN 5 THEN `count` ELSE NULL END) AS Thursday,
       AVG(CASE DAYOFWEEK(`date`) WHEN 6 THEN `count` ELSE NULL END) AS Friday
FROM   mytable

EDIT:
Given the updated expected output in the edited post, it's much easier to do - just group by the dayname:

SELECT   DAYNAME(`date`), AVG(`count`)
FROM     mytable
WHERE    DAYOFWEEK(`date`) BETWEEN 2 AND 6
GROUP BY DAYNAME(`date`)



回答2:


@Mureinik's answer also pivots the data sets. If you need the week days as rows, not columns (I'm not sure by your question), the query gets even easier (untested):

SELECT DAYNAME(`date`) AS day_of_week,
       AVG(`count`) AS average
FROM yourtable
GROUP BY DAYOFWEEK(`date`)
ORDER BY DAYOFWEEK(`date`)


来源:https://stackoverflow.com/questions/34385870/compute-average-sales-per-day-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!