Skip to content
Advertisement

An equivalent expression for MIN_BY in SQL?

In SQL we have the function MIN_BY(B,C), which returns the value of B at the minimum of C.

How would one get the same functionality, but without using the MIN_BY function?

i.e. given columns A,B,C, I want to group by A and return the value of B that corresponds to the minimum of C. I can see there must be some way to do it using OVER and PARTITION BY but am not well versed in enough to see how!

Advertisement

Answer

One method uses window functions:

select a, min(min_bc)
from (select t.*, min(b) over (partition by a order by c) as min_bc
      from t
     )
group by a;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement