[英]SQL: Count with group by problems
我的腳本有問題 - 我需要什么?
我有這張桌子:
--------------------------------
| id | ip | country |
--------------------------------
| 1 | 80.100.100.20 | CZ |
--------------------------------
| 2 | 80.100.100.20 | CZ |
--------------------------------
| 3 | 90.900.900.90 | CZ |
--------------------------------
| 4 | 55.555.555.55 | RU |
--------------------------------
這是我的“訪客”表,所以我需要統計來自國家/地區的訪客數。 在這種情況下,我需要:
2 CZ
1 RU
country = CZ 的行是 3,但 2 行具有相同的 IP 地址,因此實際訪問者是 2。
我該怎么做? 謝謝。
我正在嘗試一些這樣的:
SELECT count(DISTINCT `ip`) AS `count`, `country`
FROM `1799_visitors`
GROUP BY `ip`
返回:
1 CZ
1 CZ
1 RU
這可能很好,但我需要它們的總和。
2 CZ
1 RU
它可能通過以下解決方案解決:
SELECT count(DISTINCT `ip`) AS `count`, `country`
FROM `1799_visitors`
GROUP BY `country`
但另一方面,我還需要對所有計數進行計數,如下所示:
SELECT count(DISTINCT `ip`) AS `count`, `country`
FROM `1799_visitors`
GROUP BY `country`
結果:
CZ 2
RU 1
我需要訪問者 = 3,我正在考慮這個,但我不想使用 2 select,你有其他解決方案嗎?
SELECT SUM(count) FROM (SELECT COUNT( DISTINCT `ip` ) AS `count` , `country`
FROM `1799_visitors`
GROUP BY `country`
LIMIT 0 , 100) src;
你需要GROUP BY
ip
以及country
SELECT `country`, `ip`, COUNT(`ip`) AS `Ipcount`
FROM `1799_visitors`
GROUP BY `country`, `ip`;
結果:
country ip Ipcount
CZ 80.100.100.20 2
CZ 90.900.900.90 1
RU 55.555.555.55 1
您需要GROUP BY
僅country
:
SELECT country
, COUNT(DISTINCT ip
) AS Ipcount
FROM 1799_visitors
GROUP BY country
;
GROUP BY ip
意味着COUNT()
函數為每個ip
調用一次,因此將在每次調用時返回 1。 GROUP BY country
使用每個國家/地區的所有ip
調用函數COUNT()
。 添加DISTINCT
意味着只計算唯一 ip-address 的數量,這就是您想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.