计算每日平均值(或:星期几在日期范围内)? [英] Calculating a daily average (or: how many Mondays are in a date range?)

查看:162
本文介绍了计算每日平均值(或:星期几在日期范围内)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL表具有以下列:datetime,price_paid。
我试图计算一周中每天的平均销售额,在2个日期之间。
这意味着我需要选择销售总额,在startDate和endDate之间,按周日分组,除以每个工作日在该范围内发生的次数。



我得到了第一部分:

  SELECT DATE_FORMAT(datetime,'%a')AS field1,
轮(SUM(price_paid)/ THEVALUEIMLOOKINGFOR)AS field2
FROM Bills
WHERE date(datetime)BETWEEN'2012-01-02'AND'2012-01-09'
GROUP BY工作日(datetime)

我没有的是缺少的值:我应该划分的数字 - 每天在该范围内出现的次数。我尝试了几种解决方案,无济于事。



有人可以帮我完成我的SQL语句吗?



谢谢你的时间! b $ b

解决方案

也许我太简单了,但是考虑到你已经在工作日之前分组了,不会只计算(*)计算



so:

  SELECT DATE_FORMAT(datetime,'%a')AS field1,
round(SUM(price_paid))/ COUNT(DISTINCT(date(datetime))))AS field2
FROM Bills
WHERE date(datetime)BETWEEN'2012-01-02'AND'2012-01-09'
GROUP BY工作日(datetime)

编辑,因此在同一天不要多次计数(谢谢DRapp)


My MySQL table has the following columns: datetime, price_paid. I'm trying to calculate the average sales per day of the week, between 2 dates. This means I need select the sum of sales, between the dates startDate and endDate, grouped by weekday and divide that by the number of times every weekday occurs in that range.

I got the first part:

SELECT DATE_FORMAT(datetime, '%a') AS field1, 
round(SUM(price_paid)/ THEVALUEIMLOOKINGFOR ) AS field2 
FROM Bills 
WHERE date(datetime) BETWEEN '2012-01-02' AND '2012-01-09' 
GROUP BY weekday(datetime)

What I don't have is that missing value: the number I should divide by - number of times each day appeared in that range. I tried several solutions, to no avail.

Can someone please help me complete my SQL statement?

Thanks for your time!

解决方案

maybe I'm being too simplistic, but given that you're already grouping by weekday, wouldn't just count(*) compute the number of the given weekday in that range, for every weekday?

so:

SELECT DATE_FORMAT(datetime, '%a') AS field1, 
round(SUM(price_paid)/ COUNT(DISTINCT(date(datetime))) ) AS field2 
FROM Bills 
WHERE date(datetime) BETWEEN '2012-01-02' AND '2012-01-09' 
GROUP BY weekday(datetime)

edited so not overcounting multiple times the same day (thanks DRapp)

这篇关于计算每日平均值(或:星期几在日期范围内)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆