首页 > 解决方案 > 对于 d 中 c 行中的每个值,返回最大值为 a 的行

问题描述

我有 4 列 a ,b ,c,d

样本数据

a | b | c | d |

1 | 1 | 101 | 0
2 | 1 | 101 | 0
3 | 1 | 101 | 1
4 | 1 | 102 | 0
5 | 1 | 102 | 0
1 | 2 | 101 | 0
2 | 2 | 101 | 1

编写一个 SQL 命令,使其返回那些行,其中对于 b 中的每个 c 值,返回最大 a 的行

即期望输出

a | b | c | d |

3 | 1 | 101 | 1
5 | 1 | 102 | 0
2 | 2 | 101 | 1

标签: sql

解决方案


您可以使用相关子查询:

select t.*
from t
where t.a = (select max(t2.a) from t t2 where t2.b = t.b and t2.c = t.c);

使用 上的索引t(b, c, a),这通常具有最佳性能。

另一种方法是窗口函数:

select t.*
from (select t.*, row_number() over (partition by b, c order by a desc) as seqnum
      from t
     ) t
where seqnum = 1;

推荐阅读