简体   繁体   English

计算MySQL中每天的平均销售额

[英]Compute average sales per day in MySQL

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 

You could a series of avg calls on case expression extracting the day's name: 您可以对case表达式进行一系列avg调用,以提取当天的名称:

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 : 鉴于已编辑的帖子中更新的预期输出,它更容易做 - 只需按dayname

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

@Mureinik's answer also pivots the data sets. @Mureinik的答案也支持数据集。 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`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM