获取值的数量并以降序显示数量在新的列中的MySQL查询


使用ORDER BY DESC进行降序排序。要计数值,请使用COUNT()。例如,如果名称“John”在列中出现三次,则单独的列将显示计数3,以此类推,所有计数值将使用ORDER BY DESC按降序排列。

让我们首先创建一个表:

mysql> create table DemoTable
   -> (
   -> EmployeeName varchar(100)
   -> );
Query OK, 0 rows affected (0.85 sec)

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

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

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

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

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

mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.11 sec)

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

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

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

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

mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.18 sec)

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

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

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

mysql> select *from DemoTable;

输出

+--------------+
| EmployeeName |
+--------------+
| Sam          |
| David        |
| David        |
| Chris        |
| Robert       |
| Chris        |
| Sam          |
| Sam          |
| David        |
| Robert       |
| David        |
| Chris        |
+--------------+
12 rows in set (0.00 sec)

以下是获取值的数量并以降序显示数量在新的列中的查询:

mysql> select EmployeeName,count(EmployeeName) as Total from DemoTable
   -> group by EmployeeName
   -> order by Total DESC;

输出

+--------------+-------+
| EmployeeName | Total |
+--------------+-------+
| David        | 4     |
| Chris        | 3     |
| Sam          | 3     |
| Robert       | 2     |
+--------------+-------+
4 rows in set (0.00 sec)

更新于:2019年7月30日

4K+浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告