SQL中MIN_BY的等效表达式?

时间:2020-07-02 14:03:51

标签: sql

在SQL中,我们具有函数MIN_BY(B,C),该函数返回B的值,最小值为C

如何在不使用MIN_BY函数的情况下获得相同的功能?

即给定列A,B,C,我想按A分组并返回与B的最小值相对应的C的值。我可以看到一定有某种方法可以使用OVERPARTITION BY来做到这一点,但是对如何做到这一点却并不精通!

2 个答案:

答案 0 :(得分:1)

一种方法使用窗口函数:

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;

答案 1 :(得分:1)

只需了解一下

设置:

create table Test (a int, b int, c int);
insert into test values(1,2,3);
insert into test values(1,3,2);
insert into test values(1,4,1);
insert into test values(2,4,5);
insert into test values(2,8,4);

QUERY(对于多行且最小值为c的情况下的min(b):

select a, min(b) from Test t
where c = (select min(c) from Test b where b.a = t.a)
group by a

结果:

A   MIN(B)
1   4
2   8

Gordon Linoffs查询的结果:

A   MIN(MIN_BC)
1   2
2   4

谁是对的,谁是错的以及为什么

相关问题