如何联合“DISTINCT”和“COUNT”查询语句,以便查看 MySQL 表格列中的每个不同值出现的情况?
可以。您可以将聚合函数 COUNT(*) 与 GROUP BY 子句一起使用。首先创建一个 −
mysql> create table DemoTable1425 -> ( -> JoiningYear int -> ); Query OK, 0 rows affected (0.76 sec)
使用 insert 在表中插入一些记录 −
mysql> insert into DemoTable1425 values(2000); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1425 values(2010); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable1425 values(2015); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1425 values(2000); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1425 values(2010); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1425 values(2000); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1425 values(2010); Query OK, 1 row affected (0.10 sec)
使用 select 显示表中的所有记录 −
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
广告