[英]How to get maximum number of distinct values for multiple columns in MYSQL
我正在嘗試查找在線系統用戶使用的ip /端口組合的數量。 我想創建每個用戶名使用的最大IP和端口數的列。
我開始的基本查詢是這樣的:
Select distinct username, ip, port from users u, peers p where u.usernum=p.usernum group by username, ip, port
對於數據:
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
我希望輸出類似於以下內容:
user max_ip max_port a 1 2 b 3 2 c 2 1
我嘗試了各種形式的分組,但是沒有成功。 在此先感謝您的幫助。
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
嘗試類似:
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.