简体   繁体   English

SQL如何在单元格的值大于0时求平均值

[英]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.

相关问题 MySQL:如何检查每个组的哪些条目的值大于其相应组中的平均值? - MySQL: How do I check which entries for each group has a value greater than the average values in its corresponding group? 如何在sql中使用大于选项 - how do use greater than option in sql Postgres SQL:如何在更改平均值的现有值后重新计算平均值 - Postgres SQL : how do I recalculate average value, after an existing value from the average has been changed 当另一个值的前一个值比其前一个值大 2 时,如何增加一个变量? - How do I increment a variable when the previous value of another value is two greater than its predecessor? SQL查询,可计算历史平均值并检查当前值是否大于3 - SQL query that calculates historical average and checks if current value is greater multiple than 3 如何确定工资高于平均工资 - How to determine salaries greater than the average salary 仅当组内的每个值都大于0时,SQL SUM - SQL SUM only when each value within a group is greater than 0 SQL 当列值按日期大于 1 时基于拆分行 - SQL split row based when column value is greater than 1 by date 当它的值如下午1:00时,如何在Mysql数据库sql中获取大于或等于的值? - How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM? 大于在sql中的情况 - greater than in case when in sql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM