Skip to content
Advertisement

Oracle query to find one to many relationship in same table

I am new to query writing and need help to prepare a query in oracle . Here is the scenario, basically i need to find all the products where same product (col1) assigned to multiple codes (col2). Table1 has huge records. For purpose of explaining i have provided a mock up data

Table1

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

Output expected is

P1   B1
P1   B2
P2   B3
P2   B4
P2   B5

Advertisement

Answer

You can use analytic functions:

select t.*
from (select t.*, count(distinct col2) over (partition by col1) as cnt
      from t
     ) t
where cnt > 1;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement