Pergunta

I have a database, which hold data of customers. I need to know how many customers We have in individual city and country. I have to do it with single query.

My table is customers and I have columns city and country(both are varchar), which holds informations about it.

Desired output of query should look like this:

City | NumberOfCustomers | Country | NumberOfCustomers |
--------------------------------------------------------

Thanks

Foi útil?

Solução

select city, country, count(*) from tbl group by 1,2 with rollup

Edit to show example table and output of that query:

mysql> select * from location;
+-------+---------+
| city  | country |
+-------+---------+
| City1 | US      |
| City2 | US      |
| City2 | US      |
| City3 | CA      |
| City3 | CA      |
| City3 | JP      |
+-------+---------+
6 rows in set (0.00 sec)

mysql> select city, country, count(*) from location group by 1,2 with rollup;
+-------+---------+----------+
| city  | country | count(*) |
+-------+---------+----------+
| City1 | US      |        1 |
| City1 | NULL    |        1 |
| City2 | US      |        2 |
| City2 | NULL    |        2 |
| City3 | CA      |        2 |
| City3 | JP      |        1 |
| City3 | NULL    |        3 |
| NULL  | NULL    |        6 |
+-------+---------+----------+
8 rows in set (0.01 sec)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top