MySQL多列,单个查询

时间:2014-03-06 20:50:26

标签: mysql sql multiple-columns

我有一个数据库,其中包含客户数据。我需要知道我们在个别城市和国家拥有多少客户。我必须用单一查询来完成。

我的表是客户,我有列城市和国家(都是varchar),其中包含有关它的信息。

查询的所需输出应如下所示:

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

由于

1 个答案:

答案 0 :(得分:0)

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

编辑以显示该查询的示例表和输出:

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)