如何强制AVG包含零

时间:2019-08-13 16:29:42

标签: sql null average zero cross-join

我正在对子查询中包含零的列中的值求平均值。平均值似乎忽略了零值,而给了我一个夸张的值。

我单独拉了子查询,并且在F列(UWDays)中看到了零,这是我要平均的值。我尝试了相同的查询,但将avg(mm.UWdays)替换为avg(NULLIF(mm.days,0)),再次获得与原始拉取相同的值。

SELECT mm.month, mm.FlagA, mm.FlagB, mm.FlagC, avg(mm.UWdays) AS UWDays,

FROM (
  select date_trunc('Month', dates_table.month) as month, 
customer_table.customer_id,

Case WHEN (table1.attribute1 LIKE '%Yes%' AND table2.attribute2 LIKE '%Yes%' and table3.attribute3 NOT LIKE '%Yes%') THEN 1 ELSE 0 END AS FlagA, 
Case WHEN (table1.attribute1 LIKE '%Yes%' AND table2.attribute2 LIKE '%Yes%' AND table3.attribute3 LIKE '%Yes%') THEN 1 ELSE 0 END AS FlagB, 
Case WHEN (table1.attribute1 LIKE '%Yes%' AND table2.attribute2 LIKE '%No%' AND table3.attribute3 LIKE '%Yes%') THEN 1 ELSE 0 END AS FlagC, 


CASE WHEN (min(table1.date) is null AND max(table1.date) is null) THEN 0 ELSE count(table1.date) end AS UWDays


FROM customer_table cross dates_table  
left outer join table1 ON customer_table.customer_id= table1.customer_id
left outer join table2 on customer_table.customer_id= table2.customer_id
left outer join table3 on customer_table.customer_id= table3.customer_id

group by 1,2,3,4,5
order by 2,1) mm
GROUP BY  1,2,3,4

1 个答案:

答案 0 :(得分:1)

AVG()不会排除零。但是,它确实忽略了NULL值,所以这也许就是您的意思-尤其是因为您的查询中有LEFT JOIN个可能会生成NULL值的值。

您可以使用NULL0的值视为COALESCE()

avg(coalesce(mm.UWdays), 0)