sql - 对于 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
解决方案
您可以使用相关子查询:
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;
推荐阅读
- c++ - C 块扩展 (libBlocksRuntime) - 为 Block_copy() 使用自定义内存分配器 (Boehm GC)
- python - 在 Google Cloud 中,如何使用 Python 代码将协议和端口设置为“全部允许”
- string - 在大量字符串查询中,前缀搜索的最佳数据结构是什么?
- c - 读取的字节数总是少于询问的字节数
- sql - 在不使用递归 CTE 的情况下查找课程的所有先决条件
- python - Spyder 高亮显示我的代码,看不到文字
- c++ - 在 STL 关联容器中使用基于迭代器的搜索和使用会更快吗?
- javascript - 使用钩子在 console.log() 上反应无穷大状态,为什么会这样?
- android - 无法在 toast 中添加上下文
- c++ - 使用坐标数组在 QOpenGLWidget 中绘制 GL_LINE