There is a table (MySQL).
It's simplified structure:
day DATE val INT UNSIGNED
I need the average val
for:
- every week containing a date from the table;
- every month containing a date from the table.
What is the simplest way to do this?
MySQL
There is a table (MySQL).
It's simplified structure:
day DATE val INT UNSIGNED
I need the average val
for:
What is the simplest way to do this?
Best Answer
If you are looking to return the average
val
for each week and every month that has a date in the table, then you can implement the following.Sample data:
Weekly Average:
To get the average by week, I would
GROUP BY
both the week number and the year, using the MySQL functionsweek()
andyear()
. Then if you have data from multiple years the average will be shown by year as well (otherwise your values could be skewed). Your query would be similar to this:See SQL Fiddle with Demo. The result is:
Monthly Average:
Now to get the average
val
by month, you can use the MySQL functionsmonthname()
andyear()
.See SQL Fiddle with Demo. The result is:
Combined Result:
You did not specify if you want this data in the same query. But if you do, then you can easily use a
UNION ALL
to consolidate the data into one result set. In theUNION ALL
query, I added a column to identify the data as either month or week (but you can remove that if needed):See SQL Fiddle with Demo The
UNION ALL
will produce a combined result set similar to this: