sql - Oracle查询 - 根据另一列的顺序选择唯一的行号
问题描述
我正在尝试找到使用两列进行查询的最佳方法,一列是数字,顺序是日期:
按日期列进行选择和排序。
表 1:
col1(数字) | col2(日期) |
---|---|
1 | 02/2019 |
2 | 02/2019 |
3 | 02/2019 |
4 | 03/2019 |
2 | 04/2019 |
3 | 05/2019 |
我正在做这样的查询:
select col1, col2
from table1
order by col2 asc, col1 asc
fetch next 10;
我得到的结果也是获得第二天的值,并在 col1 结果上重复该值,如下所示:
col1(数字) | col2(日期) |
---|---|
1 | 02/2019 |
2 | 02/2019 |
3 | 02/2019 |
4 | 03/2019 |
2 | 04/2019 |
3 | 05/2019 |
但我希望过滤器仅限于这样的顺序 col1 值:
col1(数字) | col2(日期) |
---|---|
1 | 02/2019 |
2 | 02/2019 |
3 | 02/2019 |
4 | 03/2019 |
忽略将在“下一批”中出现的值,并且不会冒重复 col1 值的风险,或者获得 col2 值大于先前结果的 col1 值。
关于最好的方法的任何想法?
解决方案
如果我理解正确,您可以使用累积max()
:
select col1, col2
from (select t1.*,
max(col1) over (order by col2, col1 rows between unbounded preceding and 1 preceding) as running_max
from table1 t1
) t1
where running_max is null or col1 > running_max;
这将返回值大于前面行的值的行。
编辑:
如果您只想在第一次出现下降时返回行,那么:
select t1.*
from (select t1.*,
sum(case when prev_col1 > col1 then 1 else 0 end) over (order by col2, col1) as num_decreases
from (select t1.*,
lag(col1) over (order by col2, col1) as prev_col1
from table1 t1
) t1
where num_decreases = 0;
推荐阅读
- powershell - Powershell 导出到 csv(保持数据的原始顺序)
- eclipse - 在“运行方式”菜单中添加外部配置
- node.js - 如何在nodejs oracledb中调用PL/SQL(包中存在的程序不是PL/SQL语句)?
- sql - 表的联合列
- unity3d - 为精灵着色器添加光照支持
- c# - 如何避免为每个属性键入对象名称?
- android - Android在其他东西集中后返回焦点
- java - 无论如何都可以通过单击 Android Java 的按钮来创建卡片
- tfs - TFS 2018 服务器中缺少一些 dll
- java - Java ui4j。找不到要提交的元素