我有一张包含以下内容的表格:
| Country | Username | +---------------+----------------+ | US | John | | IT | Pedro | | US | Bob | | FR | Jill | | 192.168.1.2 | Roupraht | | 192.168.1.20 | Antonio | +---------------+----------------+
我想计算每个国家/地区的用户,而使用IP地址而不是国家/地区的用户应计为"未知";
我设法编写了以下SQL查询:
select country, count(*) as total from users group by country;
我得到了以下结果:
+-----------------+-------+ | country | total | +-----------------+-------+ | 192.168.1.2 | 1 | | 192.168.1.20 | 1 | | US | 2 | | IT | 1 | | FR | 1 | +-----------------+-------+
如何将所有IP地址统计为"未知" ?
我的目标是得到这样的表:
+-----------------+-------+ | country | total | +-----------------+-------+ | Unknown | 2 | | US | 2 | | IT | 1 | | FR | 1 | +-----------------+-------+
答案 0 :(得分:4)
如果有IP地址被视为Unknown
,您可以执行以下操作
select
country,count(*) as tot
from users
where inet_aton(country) is null
group by country
union all
select
'Unknown',count(*) as tot
from users
where inet_aton(country) is not null;
https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton
答案 1 :(得分:1)
你可以使用带有if语句的mysql LIKE语句:
select if(country LIKE '%.%.%.%', 'unknown', country), count(*) as total from users group by country;
答案 2 :(得分:0)
你可以用这个
set @unknown = (select country from table where country LIKE '%.%.%.%');
为所有IP地址设置变量'unknown'