Search code examples
oracle-databasegroup-by

How to select a rows based on column hierachical data


So I am having issues framing this but my table looks like the below:

Item LogicA LogicB ValueA ValueB
1 1 3 NameA NameAB
1 2 1 NameB NameBC
1 3 4 NameC NameCD
1 4 3 NameD NameDE
2 2 3 AAA RRR
2 3 3 BBB EEE
2 4 4 CCC FFF
2 4 4 DDD WWW

For each reference value, I want to be able to retrieve the relevant row based on hierarchy on column Logic and LogicB.

For column LogicA, check for the lowest value available and choose the corresponding row. Similarly for column Logic B look for the lowest value available and choose the relevant row.

The final output should look like below.

Item LogicA LogicB ValueA ValueB
1 1 3 NameA NameAB
1 2 1 NameB NameBC
2 2 3 AAA RRR

For Item 2, there is only 1 row as , both the lowest values for LogicA and Logic B column coincided in the same row. If they are in two different rows, there is be two rows in output as shown for item 1.


Solution

  • You can use ROW_NUMBER window function as follows:

    select t.* from
      (select t.*,
             row_number() over (partition by item order by logicA, logicB) as rn1,
             row_number() over (partition by item order by logicB, logicA) as rn2
       from your_table t) t
    where rn1 = 1 or rn2 = 1;