多列多计数

0yg35tkg  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(285)

我是sql新手。我想数一数,比如:

Select count(*) from table where col1= x and col2=x and Col3=x.

我需要在所有不同的列中计算相同的值。任何帮助都将不胜感激。

vyu0f0g1

vyu0f0g11#

可以使用条件聚合:

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

rextester演示

相关问题