Skip to content
Advertisement

SQL zero-to-many column comparison

Say I have two columns in a table, a and b. For each value of a, there can be zero-to-many values of b. If the columns are sorted by a, then by b, what is the most efficient way to mark the first value of b which is greater than the corresponding value of a in a new third column? See simplified example below.

Initial Table

a b
10 8
10 10
10 11
10 14
20 22
20 25
30 25
30 28

Desired Modified Table

a b first_greater
10 8 0
10 10 0
10 11 1
10 14 0
20 22 1
20 25 0
30 25 0
30 28 0

Advertisement

Answer

You don’t suggest a specific RDBMS but I would think the following is not too inneficient, using a simple window function and conditional case.

select a, b,
    case when b > a
      and Row_Number() 
         over (partition by a, case when b > a then 1 end order by b)=1
     then 1 else 0 
   end as first_greater
from t
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement