当计算多列中的出现次数时,mysql错误 "Operand should contain 1 column(s)"

标签 mysql sql group-by count

我想获取多列中的出现次数并将空值计为零。

这个我已经试过了。

select IFNULL((select  id, count(*) as v
from    (
        select id, s1 as val from t1
        union all select id, s2 from t1
        union all select id, s3 from t1
        union all select id, s4 from t1
        union all select id, s5 from t1
        ) sub
where   val = 3
group by id),0) as Valcount;

但它返回错误 “操作数应包含 1 列”

最佳答案

我想你想要:

select id, sum(val = 3) as valcount
from (select id, s1 as val from t1 union all
      select id, s2 from t1 union all
      select id, s3 from t1 union all
      select id, s4 from t1 union all
      select id, s5 from t1
     ) sub
group by id;

也就是说,您不想“将 NULL 值计为 0”(无论这意味着什么)。您希望在结果集中包含 30 的 id 计数。

我应该注意到forpas对你之前问题的回答是解决这个问题的正确方法。无需聚合整个数据集——这可能是一项昂贵的操作。

关于当计算多列中的出现次数时,mysql错误 "Operand should contain 1 column(s)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464089/

相关文章:

mysql - Codeigniter JOIN 使用两个表 - 需要来自两个表的数据

c# - 如何将 byte[] 转换为 varchar?

mysql - 是否可以在 UPDATE 的 WHERE 部分使用 Max()

mysql - 使用 Sequelize.js 加入特定列

mysql - 使用 MySQL 获取姓氏范围

SQL Server CTE 查询产生意外结果

python - 条件运行计数 Pandas

mysql - 添加子查询

mysql - 使用临时文件,使用 filesort with order 和 group by

mysql - 在mysql中在组之前排序