首页 > 解决方案 > 如何编写 SQL 代码来显示对数据值进行分类

问题描述

我有如下数据:

身份证国家

1 印度
2 香港
2 英国
3 智利
3 香港
4 新加坡

区域表是一个临时表,其数据如下:

国家地区

 印度 亚太地区
 香港 亚太地区
 英国 EMEA
 智利 拉丁美洲
 香港 亚太地区
 新加坡 亚太地区

如果 Country 属于同一地区,则显示地区名称 else 显示多个地区,如果 ID 具有不同的地区

输出 :

标识区域

1 亚太地区
2 多区域
3 多区域
4 亚太地区

标签: sql

解决方案


尝试Union或尝试row_number()作为其他答案之一,这很容易直接,因为row_number()不会减少行数,但有时group by取决于数据库和版本。row_number()

  Select id, "MULTIPLE 
   REGIONS" 
    from table t1 join temp t2
    on t1.country=t2.country
    Group by id having
   count(distinct 
   region) >=1
    Union
    (Select id, region
    from table t1 join temp t2
    on t1.country=t2.country
    Group by id having

   count(distinct 
   region) =1) 

推荐阅读