MySQL 多列、单查询

标签 mysql sql multiple-columns

我有一个数据库,里面保存着客户的数据。我需要知道我们在各个城市和国家有多少客户。我必须用单个查询来完成它。

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

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

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

谢谢

最佳答案

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)

关于MySQL 多列、单查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235667/

相关文章:

php - 最佳实践 : Store Large Form Values into Database

php - 常量已定义 PHP

sql - 返回所有子集中存在的 ID 的不同列表

r - 将因子水平应用于缺少因子水平的多个列

mysql - 如何使用另一个数据库的数据更新 MySQL 数据库?

c++ - MySQL 连接器 C++ 64 位从 Visual Studio 2012 中的源构建

regex - awk 从一个文件中搜索列,如果匹配从两个文件中打印列

MySQL View 永远存在

Java和MySQL连接池: avoid timeouts

mysql - 每月销售额最高的客户名称