从表列中统计 0 和 1 的数量并将其显示在两列中的 MySQL 查询是什么?


为此,您可以使用聚合函数 SUM()。我们首先创建一个表 −

mysql> create table DemoTable
(
   isMarried tinyint(1)
);
Query OK, 0 rows affected (0.84 sec)

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

mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.12 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-----------+
| isMarried |
+-----------+
|         0 |
|         1 |
|         1 |
|         0 |
|         1 |
|         1 |
|         0 |
+-----------+
7 rows in set (0.00 sec)

以下是统计一列中的 0 和 1 的数量并将其显示在两列中的查询 −

mysql> select sum(tbl.isMarried=1) as all_one_count,
   sum(tbl.isMarried=0) as all_zero_count,
   sum(tbl.isMarried in(0,1)) as all_zero_count_and_one_count
   from DemoTable tbl;

这将产生以下输出 −

+---------------+----------------+------------------------------+
| all_one_count | all_zero_count | all_zero_count_and_one_count |
+---------------+----------------+------------------------------+
|             4 |              3 |                            7 |
+---------------+----------------+------------------------------+
1 row in set (0.04 sec)

更新日期: 2019-09-25

497 个浏览量

开始你的 职业生涯

通过完成课程获得认证

开始
广告