SQL查询:在同一查询中获取高于某个值的所有内容的平均值和平均值

时间:2010-07-30 01:16:37

标签: sql mysql

我在MySQL数据库中有一列数字,还有一个时间戳列和其他内容。我想知道set参数中所有值的平均值(比如,在上周内),并且我还想要在同一时间段内所有值> gt的平均值。所以,如果我的X是10,我的值是: 0 0 10 15 20,然后我想要avg = 9avg2 = 15。我可以这样做的一种方法是使用和不使用WHERE val >= 10运行两个单独的查询,但如果可能的话,我只想在一个查询中执行此操作。有办法做到这一点吗?我看过使用CASE,但我无法正确使用语法。以下是我尝试的查询:

SELECT AVG(watts), AVG(CASE watts WHEN watts >= 10 THEN watts END CASE) FROM power WHERE meterID = 100 AND time >= '2010-07-29 00:00:00'

编辑:这就是我最终的目标。

SELECT AVG(watts) AS avg1,
AVG(IF (watts >= 10, watts, NULL)) AS avg2
FROM power
WHERE meterID = 100 AND time >= '2010-07-30 00:00:00'

4 个答案:

答案 0 :(得分:2)

这应该更好:

SELECT AVG(watts) AS average_watts,
    AVG(CASE WHEN watts > 10 THEN watts END CASE) AS average_watts_floored
FROM MyTable
WHERE meterID = 100 AND time >= '2010-07-29 00:00:00'

如果您有FROM子句,则需要WHERE子句。实际上,如果您正在计算任何类型的FROM,则需要AVG()子句。

CASE中,如果您要使用表达式而不是文字值,则应省略第一列名称。请参阅syntax documentation

我建议使用列别名。

答案 1 :(得分:2)

SELECT
   AVG(watts),
   SUM(IF(watts>10,watts,0))/SUM(IF(watts>10,1,0))
FROM FOO
WHERE
   meterID   = 100 and
   time      >= '2010-07-29 00:00:00'

版本2

SELECT
 AVG(watts),
 IF(SUM(IF(watts>10,1,0))=0,NULL,SUM(IF(watts>10,watts,0))/SUM(IF(watts>10,1,0)))
FROM FOO
WHERE
   meterID   = 100 and
   time      >= '2010-07-29 00:00:00'

答案 2 :(得分:1)

子查询可能更好。你只会打一次DB。

SELECT AVG(watts), 
    (SELECT AVG(watts) 
     WHERE meterID = 100 AND time >= '2010-07-29 00:00:00' and watts > 10) as AVG2
WHERE meterID = 100 AND time >= '2010-07-29 00:00:00';

答案 3 :(得分:0)

SELECT AVG(watts) AS average_watts,
    AVG(CASE WHEN watts > 10 THEN watts ELSE NULL END CASE) AS average_watts_floored
FROM MyTable
WHERE meterID = 100 AND time >= '2010-07-29 00:00:00'

“ELSE NULL”从平均值

中包含的begint中排除值< = 10