在 MySQL 中对多列进行计数?\n
若要对多列进行计数,请使用 CASE 语句。我们首先创建一个表:
mysql> create table countValueMultipleColumnsDemo -> ( -> Value1 int, -> Value2 int, -> Value3 int -> ); Query OK, 0 rows affected (0.62 sec)
以下是使用 insert 命令在表中插入一些记录的查询
mysql> insert into countValueMultipleColumnsDemo values(10,15,10); Query OK, 1 row affected (0.15 sec) mysql> insert into countValueMultipleColumnsDemo values(20,30,10); Query OK, 1 row affected (0.14 sec) mysql> insert into countValueMultipleColumnsDemo values(40,10,60); Query OK, 1 row affected (0.18 sec)
以下是使用 select 命令在表中显示记录的查询
mysql> select *from countValueMultipleColumnsDemo;
这将产生以下输出
+--------+--------+--------+ | Value1 | Value2 | Value3 | +--------+--------+--------+ | 10 | 15 | 10 | | 20 | 30 | 10 | | 40 | 10 | 60 | +--------+--------+--------+ 3 rows in set (0.00 sec)
以下是用于对多列进行计数的查询
mysql> SELECT (SUM(CASE WHEN Value1 = 10 THEN 1 ELSE 0 END) + -> SUM(CASE WHEN Value2 = 10 THEN 1 ELSE 0 END) + -> SUM(CASE WHEN Value3 = 10 THEN 1 ELSE 0 END)) TOTAL_COUNT -> from countValueMultipleColumnsDemo;
这将产生以下输出
+-------------+ | TOTAL_COUNT | +-------------+ | 4 | +-------------+ 1 row in set (0.00 sec)
广告