在mySQL中使用负浮点数时使用AVG()的意外结果

时间:2017-11-13 19:19:41

标签: mysql average mean

此查询

SELECT * 
FROM `rounds` 
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL 
ORDER BY `handicapDifferential` DESC, `date` DESC 
LIMIT 0, 2

在handicapDifferential中给出了-1.4-5.1两行的预期结果。字段数据类型为FLOAT。

在此查询的相同结果上使用AVG()

SELECT AVG(`handicapDifferential`) as `avg` 
FROM `rounds` 
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL 
ORDER BY `handicapDifferential` DESC, `date` DESC 
LIMIT 0, 2

给予-9.485714214188713我期望的-3.25

这是一个演示结果和问题的小提琴:http://sqlfiddle.com/#!9/32acd/3

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

将您的查询更改为

SELECT 
  AVG(items.avg) 
FROM
  (SELECT 
    `handicapDifferential` AS `avg` 
  FROM
    `rounds` 
  WHERE `user` = 18956 
    AND `handicapDifferential` IS NOT NULL 
  ORDER BY `handicapDifferential` DESC,
    `date` DESC 
  LIMIT 0, 2) items 

参考link

说明:AVG是MySQL中的聚合关键字,您应该根据需要将结果集作为输入。但是你在你的查询中称AVG为成员。