[英]SQL how to do an average when the cell has a value greater than 0
I have a SQL Query that gives an Average of Lunch times between two dates. 我有一个SQL查询,给出两个日期之间的平均午餐时间。
,AVG(DATEDIFF(SECOND, 0, lunchduration) / (60.0 * 60.0)) as avglunchduration
Right now I'm getting a very low average value because it's taking into consideration values = 0, so if in a day the employee didn't go to have lunch then my average is going lower... 现在我得到的平均值非常低,因为它考虑了值= 0,因此,如果一天中员工不去吃午餐,那么我的平均值就会降低...
What I need is only to do the average when the "lunchduration" column has a value greater than 0.
我只需要在“午餐时间”列的值大于0时进行平均。
Any clue? 有什么线索吗?
The easiest way is probably to use NULLIF()
: 最简单的方法可能是使用
NULLIF()
:
AVG(NULLIF(DATEDIFF(SECOND, 0, lunchduration) / (60.0 * 60.0), 0))
This returns NULL
if the duration is zero, and NULL values are ignored by AVG()
. 如果持续时间为零,则返回
NULL
,并且AVG()
忽略NULL值。
A more explicit case
statement is more generalizable: 更明确的
case
语句更易于推广:
AVG(CASE WHEN DATEDIFF(SECOND, 0, lunchduration) > 0
THEN DATEDIFF(SECOND, 0, lunchduration) / (60.0 * 60.0)
END)
SELECT AVG(fields)
FROM tables
WHERE lunchduration > 0
Where fields is the fields you want and tables are the tables the fields are in. 其中fields是您想要的字段,而tables是该字段所在的表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.