SQL - 月平均值而不是每日平均值

时间:2012-09-13 15:08:13

标签: sql sql-server sql-server-2008 tsql

我有一个名为值的表,其中包含3列 - 位置,值,日期

我想计算每月的平均值

到目前为止我已经

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

这会返回平均值,但是每天输入一个值,所以我每天平均而不是每月平均值,我怎样才能达到月平均值?

4 个答案:

答案 0 :(得分:9)

试试这个:

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

答案 1 :(得分:5)

如果您只想进行仅按月分组,则可以使用以下内容:

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

您甚至可以使用GROUPING SETS GROUP BY月,年,地点,然后为所有人提供总数:

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

请参阅SQL Fiddle with Demo

答案 2 :(得分:3)

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

答案 3 :(得分:0)

如果要将日期与一个月的第一天作为一天合并到一列中,也可以执行以下操作。

SELECT    Location,
          Avg(value),
          DateFromParts(Year(date), Month(date) , 1) AS FirstOfMonthDate
FROM      Value
GROUP BY  Location,
          DateFromParts(Year(date), Month(date) , 1)