如何使用单个 MySQL 查询计算特定值在列中出现的次数?


为此,你可以结合 IN() 与 GROUP BY 语句。让我们首先创建一个表 -

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.87 sec)

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

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.19 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 -

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Chris |
|  3 | David |
|  4 | Chris |
|  5 | Chris |
|  6 | John  |
|  7 | Carol |
|  8 | Sam   |
+----+-------+
8 rows in set (0.00 sec)

现在,使用单个查询计算特定值在列中出现的次数 -

mysql> select Name,count(*) AS Occurrences from DemoTable
   -> where Name in('John','Chris') group by Name;

这将产生以下输出 -

+-------+-------------+
| Name  | Occurrences |
+-------+-------------+
| John  |           2 |
| Chris |           3 |
+-------+-------------+
2 rows in set (0.00 sec)

更新于: 2019 年 7 月 30 日

881 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告