在我的postgres表中,我有两列感兴趣:id
和name
- 我的目标是仅保留id
名称中包含多个值的记录。换句话说,希望保留id
个具有多个值的所有记录,并且其中至少有一个值为B
更新:我尝试将WHERE EXISTS
添加到下面的查询中,但这不起作用
示例数据如下所示:
> test
id name
1 1 A
2 2 A
3 3 A
4 4 A
5 5 A
6 6 A
7 7 A
8 2 B
9 1 B
10 2 B
,输出如下:
> output
id name
1 1 A
2 2 A
8 2 B
9 1 B
10 2 B
如何编写查询以仅选择这些类型的记录?
答案 0 :(得分:1)
这可以使用EXISTS来完成:
select id, name
from test t1
where exists (select *
from test t2
where t1.id = t2.id
and t1.name <> t2.name) -- this will select those with multiple names for the id
and exists (select *
from test t3
where t1.id = t3.id
and t3.name = 'B') -- this will select those with at least one b for that id
答案 1 :(得分:1)
根据您的描述,您似乎想要:
select id, name
from (select t.*, min(name) over (partition by id) as min_name,
max(name) over (partition by id) as max_name
from t
) t
where min_name < max_name;
答案 2 :(得分:0)
那些他们身份不止一个名字的记录闪耀,对吧? 这可以用&#34; SQL&#34;如下:
select * from table t1
where id in (
select id
from table t2
group by id
having count(name) > 1)