多列多计数

时间:2019-01-06 17:55:27

标签: mysql sql

我是sql新手。我想数一数:

/Users/something/Development/wwwroot/trivial/config/environment.rb:5:in `<main>'
/Users/something/.rbenv/versions/2.5.1/bin/bundle:23:in `load'
/Users/something/.rbenv/versions/2.5.1/bin/bundle:23:in `<main>'

Caused by:
ArgumentError: key must be 16 bytes
/Users/something/Development/wwwroot/trivial/config/environment.rb:5:in `<main>'
/Users/something/.rbenv/versions/2.5.1/bin/bundle:23:in `load'
/Users/something/.rbenv/versions/2.5.1/bin/bundle:23:in `<main>'
Tasks: TOP => environment

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

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

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 Demo