简体   繁体   English

如何获得MYSQL中多个列的最大不同值数

[英]How to get maximum number of distinct values for multiple columns in MYSQL

I am trying to find the number of ip/port combinations used by users of an online system. 我正在尝试查找在线系统用户使用的ip /端口组合的数量。 I want to create columns with the maximum number of ips and ports used per username. 我想创建每个用户名使用的最大IP和端口数的列。

The basic query I'm starting with is this: 我开始的基本查询是这样的:

Select distinct username, ip, port from users u, peers p where u.usernum=p.usernum group by username, ip, port

For data: 对于数据:

a 1.1.1.1 12345
a 1.1.1.1 13579
b 9.8.7.6 11111
b 9.5.5.5 11115
b 9.2.2.2 11111
c 5.6.7.8 33333
c 5.6.0.0 33333

I'd like the output to resemble the following: 我希望输出类似于以下内容:

user max_ip max_port
a    1      2 
b    3      2
c    2      1

I've tried various forms of grouping, but with no success. 我尝试了各种形式的分组,但是没有成功。 Thanks in advance for your help. 在此先感谢您的帮助。

SELECT username
     , COUNT(DISTINCT ip) AS max_ip
     , COUNT(DISTINCT port) AS max_port 
FROM users u
  JOIN peers p 
    ON u.usernum = p.usernum 
GROUP BY username
SELECT username,COUNT(DISTINCT ip) AS max_ip,COUNT(DISTINCT port) AS max_port
FROM users ur, peers pr where ur.usernum = pr.usernum 
GROUP BY username

try something like: 尝试类似:

Select username, count(ip), count(distinct port) 
from users u, peers p where u.usernum=p.usernum group by username

以下查询将解决您的问题:

Select username, COUNT( distinct ip), COUNT( distinct port) from users group by username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM