小编典典

无法在MySQL中使用某些GROUP BY条件对AVG值进行ORDER BY

sql

我有一张表data_summaries。它具有这样的列如item_id INT(11)user_grouping TEXTvalue DECIMAL(10,2)

如果我尝试做一个查询组的结果通过user_grouping和他们的订单通过AVGvalue,失败:

SELECT user_grouping, AVG(value) AS avg_value, SUM(value) AS sum_value
FROM data_summaries
GROUP BY user_grouping
ORDER BY avg_value
+---------------+-----------+-----------+
| user_grouping | avg_value | sum_value |
+---------------+-----------+-----------+
| London        | 50.609733 |  18978.65 |
| Paris         | 50.791733 |  19046.90 |
| New York      | 51.500400 |   2575.02 |
| NULL          | 49.775627 |  18665.86 |
+---------------+-----------+-----------+

ORDER BY子句似乎确实在做 某些事情, 因为它确实改变了顺序:

SELECT user_grouping, AVG(value) AS avg_value, SUM(value) AS sum_value
FROM data_summaries
GROUP BY user_grouping
+---------------+-----------+-----------+
| user_grouping | avg_value | sum_value |
+---------------+-----------+-----------+
| NULL          | 49.775627 |  18665.86 |
| New York      | 51.500400 |   2575.02 |
| London        | 50.609733 |  18978.65 |
| Paris         | 50.791733 |  19046.90 |
+---------------+-----------+-----------+

在另一方面,通过订货SUMvalue作品如预期:

SELECT user_grouping, AVG(value) AS avg_value, SUM(value) AS sum_value
FROM data_summaries
GROUP BY user_grouping
ORDER BY sum_value
+---------------+-----------+-----------+
| user_grouping | avg_value | sum_value |
+---------------+-----------+-----------+
| New York      | 51.500400 |   2575.02 |
| NULL          | 49.775627 |  18665.86 |
| London        | 50.609733 |  18978.65 |
| Paris         | 50.791733 |  19046.90 |
+---------------+-----------+-----------+

如果我按分组item_id,则按AVG作品排序:

SELECT item_id, AVG(value) AS avg_value, SUM(value) AS sum_value
FROM data_summaries
GROUP BY item_id
+---------+-----------+-----------+
| item_id | avg_value | sum_value |
+---------+-----------+-----------+
|       4 | 49.318225 |  11392.51 |
|       1 | 49.737835 |  11489.44 |
|       2 | 50.420606 |  11647.16 |
|       6 | 51.024242 |  11786.60 |
|       5 | 51.456537 |  11886.46 |
|       3 | 53.213000 |   1064.26 |
+---------+-----------+-----------+

我将如何更改第一个查询以使其按平均值排序?


阅读 201

收藏
2021-04-22

共1个答案

小编典典

那是一个MySQL错误,请参阅分组查询的意外顺序,其中涉及avg()与-text列组合在一起。它仍然在MySQL
5.7.15中打开。

解决方法是,您可以将数据类型更改为例如varchar。如果不需要索引来加快速度,则转换也应该起作用:

SELECT cast(user_grouping as char(200)), AVG(value) AS avg_value, SUM(value) AS sum_value
FROM data_summaries
GROUP BY cast(user_grouping as char(200))
ORDER BY avg_value

更新:

该错误已在MySQL
5.7.17中修复

如果使用InnoDB临时表,则将查询分​​组在基于BLOB的类型的列上,并根据AVG(),VAR_POP()或STDDEV_POP()聚合函数的结果进行排序,则返回的结果将以错误的顺序返回。(缺陷号22275357,错误#79366)

2021-04-22