用1替换零结果

时间:2017-05-14 12:00:22

标签: sql sql-server

我正在计算从接近赢得的平均值。如何强制任何零的AVG结果计算为1,例如,在AE名称中,其结果为零,但我希望它为1

SELECT name AS OwnerId,
COALESCE(AVG([Opportunity.NumberOfDaysLivedinClose]),1) AS AvgTimeCtoW
FROM(SELECT
       [Opportunity.NumberOfDaysLivedinClose]
      ,name
       from [QueryExtract].[MLDataSource]
     ) as Opportunity
group by name 

MLDataSource表

name    Opportunity.NumberOfDaysLivedinClose
NS     0
NS     1
NS     0
NS     1
NS     0
NS     0
NS     0
NS     8

KB     31
KB     1
KB     53
KB     15

AE     0
AE     0
AE     1
AE     0
AE     0
AE     0
AE     0

AT     46
AT     71
AT     10

F      null

预期结果

name      AvgTimeCtoW
AE              1
FS              1
NS              1
KB             25
AT             42

1 个答案:

答案 0 :(得分:2)

我不确定你为什么要这样做,但只使用case():

SELECT name as OwnerId,
       (CASE WHEN AVG(o.NumberOfDaysLivedinClose) = 0 THEN 1
             ELSE AVG(o.NumberOfDaysLivedinClose)
        END) as AvgTimeCtoW
FROM [QueryExtract].[MLDataSource] o
GROUP BY name ;

子查询也是不必要的。