SQL:按问题计数

时间:2016-09-27 16:47:45

标签: mysql

我的脚本有问题 - 我需要什么?

我有这张桌子:

--------------------------------
| 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 SUM(count) FROM (SELECT COUNT( DISTINCT  `ip` ) AS  `count` ,  `country` 
FROM  `1799_visitors` 
GROUP BY  `country` 
LIMIT 0 , 100) src;

2 个答案:

答案 0 :(得分:1)

您需要GROUP BY country

SELECT country,COUNT(DISTINCT ip)AS Ipcount 来自1799_visitors GROUP BY country;

GROUP BY ip表示COUNT()函数会为每个ip调用一次,因此会在非常通话时返回1。 GROUP BY country调用函数COUNT(),其中包含每个国家/地区的所有ip个地址。添加DISTINCT意味着只计算唯一IP地址的数量,这是您想要的结果。

答案 1 :(得分:0)

您需要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

请参阅Fiddle Demo