在我的数据库中,我有一个包含两列的表。第一列包含日期,第二列是计数变量。我想知道是否有可能根据日期和计数来计算每个工作日的平均计数。在下面的一个小例子中:
桌子:
Date Count 02/01/2005 100 02/02/2005 200 02/03/2005 300 ... ...
输出:
Days Average Monday 120.5 Tuesday 200.2 Wednesday 300.5
您可以avg对case表达式进行一系列调用以提取当天的名称:
avg
case
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
编辑: 鉴于编辑后的帖子中已更新了预期的输出,因此操作起来容易得多-只需按dayname:分组即可:
dayname
SELECT DAYNAME(`date`), AVG(`count`) FROM mytable WHERE DAYOFWEEK(`date`) BETWEEN 2 AND 6 GROUP BY DAYNAME(`date`)