两个字段的商的avg(),在sql中给出意外的输出

kmpatx3s  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(299)

我有一个sql表,需要求两个字段商的平均值( rating , position )按其他字段分组( query_name ). 我无法理解为什么以下两个查询不会给出相同的结果:
查询1:

SELECT query_name, AVG(rating/position) AS quality
FROM queries
GROUP BY query_name

问题2:

SELECT query_name, AVG(rating*100/position)*100 AS quality
FROM queries
GROUP BY query_name

这是table:

+------------+-------------------+----------+--------+
| query_name | result            | position | rating |
+------------+-------------------+----------+--------+
| Dog        | Golden Retriever  | 1        | 5      |
| Dog        | German Shepherd   | 2        | 5      |
| Dog        | Mule              | 200      | 1      |
| Cat        | Shirazi           | 5        | 2      |
| Cat        | Siamese           | 3        | 3      |
| Cat        | Sphynx            | 7        | 4      |
+------------+-------------------+----------+--------+

这是预期输出:

Result table:
+------------+---------+
| query_name | quality |
+------------+---------+
| Dog        | 2.50    |
| Cat        | 0.66    |
+------------+---------+

但是,查询1给出了以下信息:

Result table:
+------------+---------+
| query_name | quality |
+------------+---------+
| Dog        | 2.33    |
| Cat        | 0.33    |
+------------+---------+
ijnw1ujt

ijnw1ujt1#

有些数据库做整数除法,所以 1/20 而不是 0.5 . 如果是这样的话,你的号码就会被取消。
它很容易修理。我只是乘以 1.0 :

SELECT query_name, AVG(rating * 1.0 / position) AS quality

相关问题