mysql - 多列多重计​​数

标签 mysql sql

我是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

Rextester Demo

关于mysql - 多列多重计​​数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064348/

相关文章:

java - Hibernate 与 JDBC 动态数据库连接

sql - 通过完整外连接查找多个字段的最小日期

PHP MySql 更新否则插入错误 "Warning: mysql_result()"

mysql - 触发器-mysql

java - 处理由图像标记引起的过多 HTTPRequest

mysql - 通过 SSH 复制 MySQL 数据库

mysql - 如何在sql查询中四舍五入两列的乘积

mysql - 如何优化 MySQL 查询

sql - 仅返回该值出现超过 n 次的行

c# - 如果找不到我输入的记录,如何在 SQL 中找到下一个更大的可用记录