gpt4 book ai didi

MySQL 多列、单查询

转载 作者:行者123 更新时间:2023-11-30 00:35:15 26 4
gpt4 key购买 nike

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

我的表是客户,我有城市和国家列(均为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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com