MySQL查询以获取值的计数并按降序在新列中显示计数
与DESC一起使用ORDERBY以降序排列。要计算值,请使用COUNT()
。例如,如果名称“John”出现在该列中三次,则在单独的列中将显示计数3,这样,所有计数值将使用ORDERBYDESC以降序排列。
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> EmployeeName varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('David'); mysql> insert into DemoTable values('David'); mysql> insert into DemoTable values('Chris'); mysql> insert into DemoTable values('Robert'); mysql> insert into DemoTable values('Chris'); mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('David'); mysql> insert into DemoTable values('Robert'); mysql> insert into DemoTable values('David'); mysql> insert into DemoTable values('Chris');
使用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)