我有一张表data_summaries。它具有这样的列如item_id INT(11),user_grouping TEXT和value DECIMAL(10,2)。
data_summaries
item_id INT(11)
user_grouping TEXT
value DECIMAL(10,2)
如果我尝试做一个查询组的结果通过user_grouping和他们的订单通过AVG的value,失败:
user_grouping
AVG
value
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子句似乎确实在做 某些事情, 因为它确实改变了顺序:
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 | +---------------+-----------+-----------+
在另一方面,通过订货SUM的value作品如预期:
SUM
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作品排序:
item_id
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 | +---------+-----------+-----------+
我将如何更改第一个查询以使其按平均值排序?
那是一个MySQL错误,请参阅分组查询的意外顺序,其中涉及avg()与-text列组合在一起。它仍然在MySQL 5.7.15中打开。
avg()
text
解决方法是,您可以将数据类型更改为例如varchar。如果不需要索引来加快速度,则转换也应该起作用:
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)