示例数据:
ID VALUE
1001 A
1001 B
1002 A
1002 A
1003 A
1003 B
比较标准IS ID = 1001
从这里开始,我想查看所有其他ID!= 1001 ......我需要确保:
逻辑上 - 这看起来很简单......但是我已经在键盘上打了一段时间了。
任何智慧或创可贴都会受到赞赏。
问候,
麦克
答案 0 :(得分:1)
以下是进行第一次查询的一种方法:
select s.id
from sample s
where s.id <> 101
group by s.id
having count(*) = (select count(*) from sample s where id = 101);
第二个是类似的。接下来是:
select s.id
from sample s full outer join
(select s.*
from sample s
where s.id = 101
) s100
on s.value = s100.vaue
where s.id <> 101
group by s.id
having count(*) = count(s.value) and count(s.value) = count(s100.value);
此查询的问题是存在重复项。要解决这个问题,我们需要枚举每个id的值:
select s.id
from (select s.*, row_number() over (partition by s.id, s.value order by s.id) as seqnum
from sample s
) s full outer join
(select s.*, row_number() over (partition by s.id, s.value order by s.id) as seqnum
from sample s
where s.id = 101
) s100
on s.value = s100.vaue and s.seqnum = s100.seqnum
where s.id <> 101
group by s.id
having count(*) = count(s.value) and count(s.value) = count(s100.value);
答案 1 :(得分:0)
这可以在没有PL / SQL的情况下完成
with base_values as (
select id, value
from the_table
where id = 1001
), other_values as (
select id, value
from the_table
where id <> 1001
)
select ov.id
from base_values bv
join other_values ov on bv.value = ov.value
group by ov.id
having count(distinct ov.value) = (select count(distinct value) from base_values)