获取GROUP BY语句中的平均值

时间:2018-05-17 19:10:48

标签: mysql sql

我正在尝试获取同时使用GROUP BY和ORDER BY的查询中的数字的平均值,但我不知道如何解决这个问题。

这是我的疑问:

SELECT COUNT(id) as tcount 
FROM issues 
GROUP BY location_id 
ORDER BY tcount DESC

我如何获得平均值?

4 个答案:

答案 0 :(得分:1)

使用AVG()

SELECT AVG(fieldtoaggregate) as average_value FROM table

如果您希望按字段分组的平均值,则可以使用group by。想象一下,你想要按性别分组的年龄:

SELECT AVG(age) as average_age, gender FROM tb_user GROUP BY gender ORDER BY gender ASC;

答案 1 :(得分:0)

你的问题不明确,但似乎你在寻找AVG()

SELECT COUNT(id) as tcount , avg(id) 
FROM issues 
GROUP BY location_id 
ORDER BY tcount DESC

或一般

SELECT COUNT(id) as tcount , avg(your_column) 
FROM issues 
GROUP BY location_id 
ORDER BY tcount DESC

答案 2 :(得分:0)

我想你想要:

SELECT AVG(tcount)
FROM
(
SELECT COUNT(id) as tcount 
FROM issues 
GROUP BY location_id
) sub

答案 3 :(得分:0)

只需使用AVG聚合功能:

SELECT location_id, AVG(id) as tavg 
  FROM issues 
 GROUP BY location_id 
 ORDER BY 1 DESC;

删除GROUP BY和ORDER BY会更有意义:

SELECT AVG(id) as tavg 
  FROM issues;

SQL Fiddle Demo