是否可以结合使用“ DISTINCT”和“ COUNT”查询,以便我可以看到每个不同的值在MySQL表列中出现了多少次?
是的,您可以将聚合函数COUNT(*)与GROUPBY子句一起使用。让我们首先创建一个-
mysql> create table DemoTable1425 -> ( -> JoiningYear int -> );
使用insert在表中插入一些记录-
mysql> insert into DemoTable1425 values(2000); mysql> insert into DemoTable1425 values(2010); mysql> insert into DemoTable1425 values(2015); mysql> insert into DemoTable1425 values(2000); mysql> insert into DemoTable1425 values(2010); mysql> insert into DemoTable1425 values(2000); mysql> insert into DemoTable1425 values(2010);
使用选择显示表中的所有记录-
mysql> select * from DemoTable1425;
这将产生以下输出-
+-------------+ | JoiningYear | +-------------+ | 2000 | | 2010 | | 2015 | | 2000 | | 2010 | | 2000 | | 2010 | +-------------+ 7 rows in set (0.00 sec)
以下是查询以查看每个不同值出现了多少次-
mysql> select JoiningYear,count(*) from DemoTable1425 group by JoiningYear;
这将产生以下输出-
+-------------+----------+ | JoiningYear | count(*) | +-------------+----------+ | 2000 | 3 | | 2010 | 3 | | 2015 | 1 | +-------------+----------+ 3 rows in set (0.00