繁体   English   中英

从 SQL 表中选择行,其中第一列中的条目在第二列中具有唯一值

[英]Selecting rows from an SQL table where entries in the first column have unique values in the second column

我有一个 SQL 表countryTable结构如下所示:

id | country
---+--------
 1 | US
 2 | GB
 2 | US
 3 | AU
 4 | AU
 5 | CA
 4 | US

我只想 select id 具有单个对应国家/地区的行 - 在这种情况下, output 将是

id | country
---+--------
 1 | US
 3 | AU
 5 | CA

从 ids 2 & 4 map 到(GB,US)和(AU,US),而不仅仅是单个国家。

到目前为止,我已经尝试过这个查询:

select * 
from countryTable
group by 1,2
having count(distinct country) = 1

但是,结果包括 ID 映射到多个国家/地区的行。

任何指导将不胜感激。

不要同时按 ID 和国家/地区分组,因为这将为每个组合创建一个单独的组。 相反,按 ID 分组,并使用min(country)检索那些只有一个国家/地区的 ID 的单个国家/地区值。

select id, min(country) country
from countryTable
group by id
having count(distinct country) = 1;

首先,您需要收集唯一 ID。 您的 group by 是按 id 和 country 分组的,它们都是一对不同的。 您可以通过执行子查询或临时 WITH 查询以及对结果进行内部联接来做到这一点。

with uniqueIds(id) as (select id from countryTable
group by id
having count(*)=1)
select countryTable.* from countryTable
inner join uniqueIds u on countryTable.id = u.id

关于如何使用 WITH 子句的信息: https://www.geeksforgeeks.org/sql-with-clause/

您只需要检查是否存在具有相同id和不同country /地区值的行,如下所示

SELECT * FROM data d
WHERE NOT EXISTS (
    SELECT 1 FROM data dd 
    WHERE dd.id = d.id AND dd.country != d.country
)

Output

ID 国家
1 我们
3 澳大利亚
5

您可以在此处查看工作演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM