我是sql新手。我想计算如下内容:
Select count(*) from table where col1= x and col2=x and Col3=x.
我需要计算所有不同列中的相同值。 任何帮助将不胜感激。
最佳答案
您可以使用条件聚合:
Select sum(case when col1='x' then 1 else 0 end) as count_col1,
sum(case when col2='x' then 1 else 0 end) as count_col2,
sum(case when col3='x' then 1 else 0 end) as count_col3
from tab;
如果您想获得这些计数值的总和,请将上述查询视为内部查询并使用以下内容:
Select q.*,
q.count_col1 + q.count_col2 + q.count_col3 whole_sum
from
(
Select sum(case when col1='x' then 1 else 0 end) as count_col1,
sum(case when col2='x' then 1 else 0 end) as count_col2,
sum(case when col3='x' then 1 else 0 end) as count_col3
from tab
) q
关于mysql - 多列多重计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064348/