如何计算 MySQL 中的列的独特值?
你需要使用 GROUP BY 实现此目的。我们先创建一个表 −
mysql> create table DemoTable ( StudentFirstName varchar(20) ); Query OK, 0 rows affected (0.74 sec)
使用 insert 命令向表插入记录 −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (1.34 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Bob'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.55 sec) mysql> insert into DemoTable values('Bob'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.14 sec)
使用 select 语句从表中显示所有记录 −
mysql> select * from DemoTable;
将产生以下输出 −
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | John | | John | | Bob | | David | | Bob | | Carol | | Robert | +------------------+ 9 rows in set (0.00 sec)
以下是统计 MySQL 中列的唯一值的查询 −
mysql> select StudentFirstName,count(*) from DemoTable group by StudentFirstName;
将产生以下输出 −
+------------------+----------+ | StudentFirstName | count(*) | +------------------+----------+ | John | 3 | | Carol | 2 | | Bob | 2 | | David | 1 | | Robert | 1 | +------------------+----------+ 5 rows in set (0.00 sec)
广告