首页 > 解决方案 > 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 值。

关于最好的方法的任何想法?

标签: sqloracle

解决方案


如果我理解正确,您可以使用累积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;

推荐阅读