要计算非重复值,可以在聚合函数中使用非重复值count()
。
语法如下-
select count(distinct yourColumnName) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询-
mysql> create table DistinctDemo −> ( −> Name varchar(200) −> );
对于我们的示例,让我们在表中插入重复的记录。插入记录的查询如下-
mysql> insert into DistinctDemo values('John'); mysql> insert into DistinctDemo values('Sam'); mysql> insert into DistinctDemo values('John'); mysql> insert into DistinctDemo values('Johnson'); mysql> insert into DistinctDemo values('John'); mysql> insert into DistinctDemo values('Johnson'); mysql> insert into DistinctDemo values('Sam'); mysql> insert into DistinctDemo values('Johnson');
在select语句的帮助下显示所有记录。显示所有记录的查询如下-
mysql> select *from DistinctDemo;
以下是显示一些重复记录的输出-
+---------+ | Name | +---------+ | John | | Sam | | John | | Johnson | | John | | Johnson | | Sam | | Johnson | +---------+ 8 rows in set (0.00 sec)
这是可用于计算表中不同值的查询-
mysql> select count(distinct Name) as DistinctValues from DistinctDemo;
以下是输出-
+----------------+ | DistinctValues | +----------------+ | 3 | +----------------+ 1 row in set (0.01 sec)
结果i3告诉我们表中有3个不同的值。