6

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

我想算出每个月的平均值

到目前为止我有

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

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

4

4 回答 4

14

试试这个:

SELECT    Location,
          Avg(value),
          month(date),
          year(date)
FROM      Value
GROUP BY  Location,
          month(date),
          year(date)
于 2012-09-13T15:10:12.397 回答
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

于 2012-09-13T15:10:11.083 回答
4
SELECT
     Location,
     year(date),
     month(date),
     Avg(value)
FROM
     Value
GROUP BY
     Location,
     year(date),
     month(date)
于 2012-09-13T15:10:08.303 回答
0

如果您想将日期合并到一个列中,并以当月的第一天为日期,也可以按以下方式进行操作。

SELECT    Location,
          Avg(value),
          DateFromParts(Year(date), Month(date) , 1) AS FirstOfMonthDate
FROM      Value
GROUP BY  Location,
          DateFromParts(Year(date), Month(date) , 1)
于 2020-09-15T03:10:08.883 回答