統計 MySQL 表中記錄出現的次數並在新列中顯示結果?


為此,請與 GROUP BY 子句一起使用 COUNT(*)。我們首先建立一個表 -

mysql> create table DemoTable1942
   (
   Value int
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select * from DemoTable1942;

這將產生以下輸出 -

+-------+
| Value |
+-------+
|     1 |
|     2 |
|     3 |
|     2 |
|     3 |
|     3 |
|     1 |
+-------+
7 rows in set (0.00 sec)

此處是用於統計出現次數的查詢

mysql> select Value, count(*) from DemoTable1942
   group by Value;

這將產生以下輸出 -

+-------+----------+
| Value | count(*) |
+-------+----------+
|     1 |        2 |
|     2 |        2 |
|     3 |        3 |
+-------+----------+
3 rows in set (0.00 sec)

更新於:31-12-2019

2K+ 次瀏覽

職業 起點

完成課程並獲得認證

開始
廣告
© . All rights reserved.