我有一个包含以下各列的收集表:
id (INT)
col1 (VARCHAR)
col2 (VARCHAR)
value (INT)
我想分别通过col1
和col2
计算平均值 ,以获得这样的响应:
{
averageByCol1: {col1Value1: 23, col1Value2: 44},
averageByCol2: {col2Value1: 33, col2Value2: 91}
}
试图在GROUP BY中使用多个列,但这将合并这些列:
SELECT
CONCAT(col1, col2, AVG(value))
FROM table1
GROUP BY col1, col2
也尝试了子查询,但它给了我Subquery returns more than 1 row
错误:
SELECT
(SELECT
CONCAT(col1, AVG(value))
FROM table1
GROUP BY col1) AS col1Averages,
(SELECT
CONCAT(col2, AVG(value))
FROM table1
GROUP BY col2) AS col2Averages;
使用Mysql v5.5。
使用示例数据进行编辑:
id col1 col2 value
1 v1 b1 34
2 v2 b1 65
3 v1 b1 87
4 v1 b2 78
5 v2 b2 78
6 v1 b2 12
分别由v1,v2,b1和b2求value
的平均值。
答案 0 :(得分:1)
对要计算平均值的每一列使用UNION
SELECT col1 as col_key, avg(value) as average
FROM test
GROUP BY col1
UNION
SELECT col2, avg(value)
FROM test
GROUP BY col2
答案 1 :(得分:1)
这将起作用:
select avg(value),col1 from Table1 group by col1
union all
select avg(value),col2 from Table1 group by col2
答案 2 :(得分:0)
如果您要查询2个单独的结果:
SELECT col1, AVG(value) AS average1
from table1
GROUP BY col1
ORDER BY col1
和
SELECT col2, AVG(value) AS average2
from table1
GROUP BY col2
ORDER BY col2