获取唯一值的计数的 MySQL 查询?


要计算列中的唯一值,需要使用关键字 DISTINCT。为了理解它是如何实现的,让我们创建一个表。创建表的查询如下 -

mysql> create table UniqueCountByIPAddress
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserHits int,
   -> UserIPAddress varchar(50),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.69 sec)

使用 insert 命令在表中插入一些记录。查询如下 -

mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(10,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(10,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.1');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.2');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.2');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.28 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录。查询如下 -

mysql> select *from UniqueCountByIPAddress;

以下是输出 -

+----+----------+--------------+
| Id | UserHits | UserIPAddress|
+----+----------+--------------+
|  1 |       10 | 127.0.0.1    |
|  2 |       10 | 127.0.0.1    |
|  3 |       20 | 127.0.0.1    |
|  4 |       20 | 127.0.0.1    |
|  5 |       20 | 127.0.0.2    |
|  6 |       20 | 127.0.0.2    |
|  7 |       30 | 127.0.0.2    |
|  8 |       30 | 127.0.0.2    |
|  9 |       30 | 127.0.0.2    |
+----+----------+--------------+

以下是计算列 'UserIPAddress' 上唯一值数量的查询 -

mysql> select UserHits,count(distinct UserIPAddress) as TotalHits
   -> from UniqueCountByIPAddress group by UserHits;

以下是输出 -

+----------+-----------+
| UserHits | TotalHits |
+----------+-----------+
|       10 |         1 |
|       20 |         2 |
|       30 |         1 |
+----------+-----------+
3 rows in set (0.05 sec)

更新日期: 30-Jul-2019

413 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始
广告