1

只有当值大于零时,我才想取行的平均值。但是,我收到以下错误:

'列 'Daily.Rad' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 中...'

代码:

SELECT Date,
       AVG([Speed]) as [Speed], 

       CASE WHEN [Rad] > 0.0
            THEN AVG([Rad])
            ELSE 0.0
       END AS [Rad], 

       AVG([Pressure]) as [Pressure], 

       FROM Daily 
WHERE MONTH(Date) = MONTH('08/31/2011')  
GROUP BY Date
4

4 回答 4

1

您需要将 CASE 子句放在 AVG 函数中。

SELECT Date,
       AVG([Speed]) as [Speed], 
       AVG (
       CASE WHEN [Rad] > 0.0
            THEN [Rad]
            ELSE 0.0
       END) AS [Rad], 

       AVG([Pressure]) as [Pressure], 
        Date
       FROM Daily 
WHERE MONTH(Date) = MONTH('08/31/2011')  
GROUP BY Date
于 2012-08-20T03:49:09.410 回答
1

如果您想要Rad所有行的平均值,而忽略负值,其他人已经给出了正确的答案。相反,如果您只需要正值的Rad平均值,那么您必须自己计算:

SELECT Date,
       AVG([Speed]) as [Speed], 

       SUM(CASE WHEN Rad>0.0 THEN Rad ELSE 0.0 END)
       /SUM(CASE WHEN Rad>0.0 THEN 1 ELSE 0 END) as Rad,

       AVG([Pressure]) as [Pressure], 

       FROM Daily 
WHERE MONTH(Date) = MONTH('08/31/2011')  
GROUP BY Date
于 2012-08-20T06:01:49.250 回答
0

如果您试图从平均值中排除负 Rad 值,那么我认为您想要的是:

SELECT Date,
AVG([Speed]) as [Speed], 

AVG(CASE WHEN [Rad] > 0.0
         THEN [Rad]
         ELSE 0.0
END) AS [Rad], 

AVG([Pressure]) as [Pressure] 

FROM Daily 
WHERE MONTH(Date) = MONTH('08/31/2011')  
GROUP BY Date
于 2012-08-20T03:48:35.490 回答
0

这将消除负值并平均其余值。此外,where 子句将导致更好的性能。

SELECT Date,
       AVG([Speed]) as [Speed], 

       coalesce(nullif( abs([Rad]), -[Rad]), 0) AS [Rad], 
       -- OR
       coalesce(AVG(CASE WHEN [Rad] > 0 THEN [Rad] END), 0) [Rad]

       AVG([Pressure]) as [Pressure], 

       FROM Daily 
WHERE Date >= dateadd(month, datediff(month,  0, '2011-08-31'), 0)
  AND Date <  dateadd(month, datediff(month, -1, '2011-08-31'), 0)
GROUP BY Date
于 2012-08-20T08:24:48.383 回答