如果,SQL中的Else或Case语句

时间:2012-08-20 03:29:30

标签: sql-server tsql

我想仅在值大于零时才取平均值。但是,我收到以下错误:

  

'列'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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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