Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and filter mysql results

Tags:

mysql

i have a table with the following content :

| Country       | Username       |
+---------------+----------------+
| US            | John           |
| IT            | Pedro          |
| US            | Bob            |
| FR            | Jill           |
| 192.168.1.2   | Roupraht       |
| 192.168.1.20  | Antonio        |
+---------------+----------------+

I want to count the users of each country, and the users with IP address instead of country should be counted like "unknown";

i have managed to write the following SQL query :

select country, count(*) as total from users group by country;

And i got the following result :

+-----------------+-------+
| country         | total |
+-----------------+-------+
| 192.168.1.2     |     1 |
| 192.168.1.20    |     1 |
| US              |     2 |
| IT              |     1 |
| FR              |     1 |
+-----------------+-------+

how can i count all the IP addresses as an "unknown" ?
my goal is to get table like this :

+-----------------+-------+
| country         | total |
+-----------------+-------+
| Unknown         |     2 |
| US              |     2 |
| IT              |     1 |
| FR              |     1 |
+-----------------+-------+
like image 617
Zibar Avatar asked May 19 '15 10:05

Zibar


People also ask

Can filters be used on query results?

You can use filters to display specific records in a form, report, query, or datasheet, or to print only certain records from a report, table, or query.

Which statement would you use to filter data in MySQL?

One of the most important requirements when retrieving data is to be able to filter that data so that the only rows returned are those which match specified search criteria. This is achieved in MySQL using the WHERE clause in conjunction with the SELECT statement.


2 Answers

If there are IP address to be considered as Unknown you can do the following trick

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

like image 56
Abhik Chakraborty Avatar answered Oct 11 '22 03:10

Abhik Chakraborty


you can use mysql LIKE statement with if statement:

select if(country LIKE '%.%.%.%', 'unknown', country), count(*) as total from users group by country;
like image 31
Vladyslav Sheruda Avatar answered Oct 11 '22 02:10

Vladyslav Sheruda