我想获取多列中的出现次数并将空值计为零。
这个我已经试过了。
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”(无论这意味着什么)。您希望在结果集中包含 3
且 0 的 id
计数。
我应该注意到forpas对你之前问题的回答是解决这个问题的正确方法。无需聚合整个数据集——这可能是一项昂贵的操作。
关于当计算多列中的出现次数时,mysql错误 "Operand should contain 1 column(s)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464089/