如何计算 MySQL 中具有特定值的列数量?


以下是语法 -

select
sum(yourColumnName1+yourColumnName2+yourColumnName3...N) as `anyAliasName1`,
sum(yourColumnName1 and yourColumnName2 and yourColumnName3….N) as anyAliasName
from yourTableName;

我们来创建一张表 -

mysql> create table demo36
−> (
−> id int not null auto_increment primary key,
−> value1 int,
−> value2 int,
−> value3 int
−> );
Query OK, 0 rows affected (1.68 sec)

使用 insert 命令向表中插入一些记录 -

mysql> insert into demo36(value1,value2,value3) values(1,0,0);
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo36(value1,value2,value3) values(1,0,1);
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo36(value1,value2,value3) values(1,1,1);
Query OK, 1 row affected (0.22 sec)

mysql> insert into demo36(value1,value2,value3) values(0,1,0);
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo36(value1,value2,value3) values(1,1,0);
Query OK, 1 row affected (0.10 sec)

使用 select 语句从表中显示记录 -

mysql> select *from demo36;

这将生成以下输出 -

+----+--------+--------+--------+
| id | value1 | value2 | value3 |
+----+--------+--------+--------+
| 1  | 1      | 0      | 0      |
| 2  | 1      | 0      | 1      |
| 3  | 1      | 1      | 1      |
| 4  | 0      | 1      | 0      |
| 5  | 1      | 1      | 0      | 
+----+--------+--------+--------+
5 rows in set (0.00 sec)

以下是统计 MySQL 中特定值列数的查询 -

mysql> select
−> sum(value1+value2+value3) as `Total_Number_Of_1`,
−> sum(value1 and value2 and value3) as `Total_Number_Of_Rows_With_1`
−> from demo36;

这将生成以下输出 -

+-------------------+-----------------------------+
| Total_Number_Of_1 | Total_Number_Of_Rows_With_1 |
+-------------------+-----------------------------+
|                 9 |                           1 |
+-------------------+-----------------------------+
1 row in set (0.00 sec)

更新于:19-11-2020

249 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告