SQL - monthly average, not average daily

I have a table with values ​​containing 3 columns - Location, value, date

I want to work out the average value per month

still i

SELECT Location, Avg(value), date FROM Value GROUP BY Location, date 

This returns averages, but the value is entered daily, so I have an average value per day, not a month, how can I achieve a monthly average?

+4
source share
3 answers

try the following:

 SELECT Location, Avg(value), month(date), year(date) FROM Value GROUP BY Location, month(date), year(date) 
+7
source

You can use the following if you want to group only a month:

 SELECT Location, Avg(value) AvgVal, Month(date) Mnth FROM Value GROUP BY Location, Month(date) 

You can even use GROUPING SETS , which will be GROUP BY Month, year, location, and then give you a common ground for everyone:

 SELECT Location, Avg(value) AvgVal, Month(dt) Mnth, Year(dt) Yr FROM yourtable GROUP BY GROUPING SETS((Month(dt), Year(dt), Location), (Location)); 

See SQL Fiddle with Demo

+5
source
 SELECT Location, year(date), month(date), Avg(value) FROM Value GROUP BY Location, year(date), month(date) 
+4
source

Source: https://habr.com/ru/post/1434023/


All Articles