如果您希望返回val
表中包含日期的每周和每月的平均值,则可以执行以下操作。
样本数据:
CREATE TABLE yourtable (`day` datetime, `val` int);
INSERT INTO yourtable (`day`, `val`)
VALUES
('2012-01-01 00:00:00', 465),
('2012-01-02 00:00:00', 896),
('2012-08-15 00:00:00', 678),
('2012-09-01 00:00:00', 324),
('2012-12-02 00:00:00', 74),
('2012-12-03 00:00:00', 65),
('2012-12-04 00:00:00', 35);
Run Code Online (Sandbox Code Playgroud)
每周平均:
要按周获得平均值,我将GROUP BY
使用 MySQL 函数week()
和year()
. 然后,如果您有多年的数据,则平均值也将按年份显示(否则您的值可能会出现偏差)。您的查询将类似于:
select week(day) Week,
year(day) Year,
avg(val) WeekAvg
from yourtable
group by week(day), year(day)
Run Code Online (Sandbox Code Playgroud)
请参阅SQL Fiddle with Demo。结果是:
| WEEK | YEAR | WEEKAVG |
-------------------------
| 1 | 2012 | 680.5 |
| 33 | 2012 | 678 |
| 35 | 2012 | 324 |
| 49 | 2012 | 58 |
Run Code Online (Sandbox Code Playgroud)
月平均:
现在要val
按月获得平均值,您可以使用 MySQL 函数monthname()
和year()
.
select monthname(day) Month,
year(day) Year,
avg(val) AvgValue
from yourtable
group by monthname(day), year(day)
Run Code Online (Sandbox Code Playgroud)
请参阅SQL Fiddle with Demo。结果是:
| MONTH | YEAR | AVGVALUE |
-------------------------------
| August | 2012 | 678 |
| December | 2012 | 58 |
| January | 2012 | 680.5 |
| September | 2012 | 324 |
Run Code Online (Sandbox Code Playgroud)
综合结果:
您没有指定是否要在同一查询中使用此数据。但是如果这样做,那么您可以轻松地使用 aUNION ALL
将数据合并到一个结果集中。在UNION ALL
查询中,我添加了一列以将数据标识为月或周(但您可以根据需要将其删除):
select monthname(day) Month,
year(day) Year,
avg(val) AvgValue,
'MonthAvg' Source
from yourtable
group by monthname(day), year(day)
union all
select week(day) Week,
year(day) Year,
avg(val) WeekAvg,
'WeekAvg' Source
from yourtable
group by week(day), year(day)
Run Code Online (Sandbox Code Playgroud)
请参阅SQL拨弄演示 中UNION ALL
会产生组合的结果集与此类似:
| MONTH | YEAR | AVGVALUE | SOURCE |
------------------------------------------
| August | 2012 | 678 | MonthAvg |
| December | 2012 | 58 | MonthAvg |
| January | 2012 | 680.5 | MonthAvg |
| September | 2012 | 324 | MonthAvg |
| 1 | 2012 | 680.5 | WeekAvg |
| 33 | 2012 | 678 | WeekAvg |
| 35 | 2012 | 324 | WeekAvg |
| 49 | 2012 | 58 | WeekAvg |
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12766 次 |
最近记录: |