分别按多列平均

9lowa7mx  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(283)

我有一个包含以下列的集合表1:

id (INT)
col1 (VARCHAR)
col2 (VARCHAR)
value (INT)

我想分别计算平均数 col1 通过 col2 有这样的回答:

{
    averageByCol1: {col1Value1: 23, col1Value2: 44},
    averageByCol2: {col2Value1: 33, col2Value2: 91}
}

尝试在“分组依据”中使用多个列,但这会合并以下列:

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

想要平均 value 由v1、v2、b1和b2独立完成。

amrnrhlw

amrnrhlw1#

这将起作用:

select avg(value),col1 from Table1 group by col1
  union all
  select avg(value),col2 from Table1 group by col2

sql语句fiddle:http://sqlfiddle.com/#!9/c1f111/5/0年

ix0qys7i

ix0qys7i2#

如果要对单独的结果进行两次查询:

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
5cnsuln7

5cnsuln73#

对要计算平均值的每列使用并集

SELECT col1 as col_key, avg(value) as average
FROM test
GROUP BY col1
UNION
SELECT col2, avg(value)
FROM test
GROUP BY col2

相关问题