Oracle查询在同一表中查找一对多关系

时间:2020-07-23 17:16:50

标签: sql oracle

我是查询编写的新手,需要帮助来准备oracle中的查询。在这种情况下,基本上我需要找到所有将相同产品(col1)分配给多个代码(col2)的产品。表1记录很多。为了解释起见,我提供了一个模拟数据

表1

Col1 col2 col3 col4
P1    B1   T1   I
P1    B1   T2   G
P1    B2   T1   I
P2    B3   T1   I
P2    B4   T2   I
P2    B5   T2   I
P6    B6   T1   I
P7    B7   T1   I
P8    B8   T2   I

预期输出为

P1   B1
P1   B2
P2   B3
P2   B4
P2   B5

2 个答案:

答案 0 :(得分:1)

您可以使用分析功能:

select t.*
from (select t.*, count(distinct col2) over (partition by col1) as cnt
      from t
     ) t
where cnt > 1;

答案 1 :(得分:0)

解析查询可能是解决之道,尽管它可能会导致我认为的海量数据出现问题。您不能通过简单的分组方法来同时获得两个值。只需通过以下方式获得col1值:

select col1
from t
group by col1
having count(distinct col2) > 1;

但这并不能真正帮助您。它可以用作子查询:

select col1, col2
from t
where col1 in (
  select col1
  from t
  group by col1
  having count(distinct col2) > 1
)
order by col1, col2;

但是现在您必须两次打赌,这可能比分析方法贵。并且您必须添加distinct才能准确获得所需的输出。

您还可以使用某种类型的自联接,例如与exists()

select col1, col2
from t t1
where exists (
  select null
  from t t2
  where t2.col1 = t1.col1
  and t2.col2 != t1.col2
)
order by col1, col2;

但是同样,您需要检查性能(并使用distinct)。

db<>fiddle显示这些内容,以及@Gordon的分析查询进行比较(以及@oratom的注释以显示不符合您的期望)。

相关问题