Mysql:查询从日期范围获得平均值,最大值和最小值

时间:2016-03-22 17:09:00

标签: mysql

我的桌子上只有三个字段:

userID (integer, key, autoincrement)
date (Y-m-d format)
hits (integer)

我每天都会填充数据(userID和日期是唯一的)所以我的值如下:

1 | '2016-01-01' | 200
1 | '2016-01-02' | 289
2 | '2016-01-15' | 389
2 | '2016-01-16' | 390
....

我怎么能得到:

  • 上周的平均每日点击次数?
  • 上个月的平均每周点击次数?
  • 上周每日点击次数最多
  • 上周每天最低点数

t h n n s s

2 个答案:

答案 0 :(得分:1)

SELECT AVG(hits) FROM table WHERE date BETWEEN 'beginning' and 'end';

这里:'开头'是'yyyy-mm-dd'格式的周或月的开始日期; 'end'是相同的,但结束日期。

SELECT MAX(hits) FROM table WHERE date BETWEEN 'beginning' and 'end';
SELECT MIN(hits) FROM table WHERE date BETWEEN 'beginning' and 'end';

示例:

SELECT AVG(hits) FROM table WHERE date BETWEEN '2016-01-01' and '2016-01-31';
SELECT MAX(hits) FROM table WHERE date BETWEEN '2016-01-01' and '2016-01-31';

答案 1 :(得分:1)

对于上周的平均每日点击次数,请尝试:

SELECT date, AVG(hits) 
FROM table 
WHERE date <= '2016-03-19' AND date >= '2016-03-13' 
GROUP BY date

Max和Min,替代&#34; AVG&#34;为&#34; MAX&#34;或者&#34; MIN&#34;。

相关问题