MySQL查询以计算重复的ID值,并将结果显示在单独的列中
要计算重复的ID值,请使用聚合函数COUNT()
和GROUPBY。让我们首先创建一个表-
mysql> create table DemoTable ( Id int, Name varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(50,'Chris'); mysql> insert into DemoTable values(51,'David'); mysql> insert into DemoTable values(51,'Mike'); mysql> insert into DemoTable values(50,'Sam');
使用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)