请求编写SQL查询:按国家统计客户数量(GB与UK视为同一国家)
SQL Query to Count Customers by Country (Grouping GB & UK as One)
First, let's recap your table data for clarity:
| Name | Country |
|---|---|
| A | UK |
| B | CN |
| C | IN |
| D | GB |
| E | CN |
| F | GB |
| H | UK |
| I | IN |
To count customers per country while treating GB and UK as the same region, you can use a CASE statement to standardize those country codes into a single label, then group and count. This approach works across most SQL databases (PostgreSQL, MySQL, SQL Server, etc.):
SELECT CASE WHEN Country IN ('GB', 'UK') THEN 'United Kingdom' ELSE Country END AS standardized_country, COUNT(*) AS customer_count FROM Customers GROUP BY standardized_country;
How this works:
- The
CASEexpression checks if the country is eitherGBorUK, replacing both with "United Kingdom" (feel free to swap this label for something like "UK/GB" if that fits your needs better). - We group by the standardized country name, then use
COUNT(*)to calculate the total number of customers in each group.
Expected Output:
| customer_count |
|---|
| 4 |
| 2 |
| 2 |
If you're using MySQL and prefer a more concise syntax, you can use the IF function instead of CASE:
SELECT IF(Country IN ('GB', 'UK'), 'United Kingdom', Country) AS standardized_country, COUNT(*) AS customer_count FROM Customers GROUP BY standardized_country;
内容的提问来源于stack exchange,提问作者Iqra Aslam
相关产品推荐
相关产品推荐

