我正在使用按功能分组从我的小商店购买一些产品,如:
select name, ProductID from blog group by ProductID
+----------------------------------------------------------+
| name |
+----------------------------------------------------------+
| AAA |
| BBBB |
| CCCC |
| DDDDDDDD |
+----------------------------------------------------------+
是否可以在groupby函数中获取平均长度名称?
编辑(来自OP,置于答案中):
myysql> select length(name) as len, name from product where article=40 order by len asc;
+------+----------------------------------------------------------+
| len | name |
+------+----------------------------------------------------------+
| 3 | aaa |
| 6 | BBBBBB |
| 6 | CCCCCC |
| 8 | dddddddd |
+------+----------------------------------------------------------+
4 rows in set (0.00 sec)
通过这个例子,我需要得到一个像BBBBBB或CCCCCC(AVG?)的值
答案 0 :(得分:2)
你的例子没有获得平均长度名称,因为没有这样的东西。平均长度为(8 + 3 + 6 + 6)/ 4 = 5.75。它不存在。我想你想要中位数,这个数字是50%更大,50%更小。
这是获得中位数的一种方法(假设名称不包含逗号,并且连接不超过某些限制):
select ProductID,
substring_index(substring_index(group_concat(name order by length(name) separator '||'
), '||', 1 + count(*)/2
), '||', -1) as MedianLengthName
from blog
group by ProductID;
答案 1 :(得分:0)
尝试此查询:
SELECT AVG(CHAR_LENGTH(name)) AS avg FROM tbl;
答案 2 :(得分:0)
如果您正在寻找平均值(这意味着您必须接受该十进制值之上和之下的整数),您可以使用:
SELECT *
FROM (
SELECT AVG(CHAR_LENGTH(name)) AS average
FROM product) AS calculated
JOIN product
ON CHAR_LENGTH(name) BETWEEN FLOOR(average) AND CEILING(average);