如何使用單個 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 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告