如何計算 MySQL 中同值行數?


如需統計同值行的數量,可使用 COUNT(*) 和 GROUP BY 函式。語法如下:-

SELECT yourColumName1, count(*) as anyVariableName from yourTableName GROUP BY yourColumName1;

為便於理解以上語法,我們首先建立一個表。建立表的查詢如下:-

mysql> create table RowWithSameValue
   −> (
   −> StudentId int,
   −> StudentName varchar(100),
   −> StudentMarks int
   −> );
Query OK, 0 rows affected (0.55 sec)

插入一些同值記錄。在此,對於我們的示例,我們為不止一名學生添加了相同的分數。插入記錄的查詢如下:-

mysql> insert into RowWithSameValue values(100,'Carol',89);
Query OK, 1 row affected (0.21 sec)

mysql> insert into RowWithSameValue values(101,'Sam',89);
Query OK, 1 row affected (0.15 sec)

mysql> insert into RowWithSameValue values(102,'John',99);
Query OK, 1 row affected (0.12 sec)

mysql> insert into RowWithSameValue values(103,'Johnson',89);
Query OK, 1 row affected (0.15 sec)

現在,您可以顯示所有我們上面插入的記錄。顯示所有記錄的查詢如下:-

mysql> select *from RowWithSameValue;

以下是輸出:-

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|       100 | Carol       |           89 |
|       101 | Sam         |           89 |
|       102 | John        |           99 |
|       103 | Johnson     |           89 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)

實現我們最開始討論的語法來統計同值行:-

mysql> SELECT StudentMarks, count(*) as SameValue from RowWithSameValue GROUP BY StudentMarks;

以下是顯示多值計數的輸出:-

+--------------+-----------+
| StudentMarks | SameValue |
+--------------+-----------+
|           89 |         3 |
|           99 |         1 |
+--------------+-----------+
2 rows in set (0.00 sec)

更新於:30-07-2019

3K+ 瀏覽

啟動您的職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.