MySQL 查詢用於計算重複的 ID 值並在單獨的列中顯示結果


要計算重複的 ID 值,請使用聚合函式 COUNT() 和 GROUP BY。我們首先建立一個表 -

mysql> create table DemoTable
(
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (1.30 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values(50,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(51,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(51,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(50,'Sam');
Query OK, 1 row affected (0.17 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下的輸出 −

+------+-------+
| Id   | Name  |
+------+-------+
|   50 | Chris |
|   51 | David |
|   51 | Mike  |
|   50 | Sam   |
+------+-------+
4 rows in set (0.00 sec)

以下是查詢在新的列中顯示重複 ID 值的數量 −

mysql> select Id,count(Name) as Count
   from DemoTable
   group by Id;

這將產生以下的輸出 −

+------+-------+
| Id   | Count |
+------+-------+
|   50 |     2 |
|   51 |     2 |
+------+-------+
2 rows in set (0.00 sec)

更新於: 2019 年 10 月 1 日

822 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.