【问题标题】:Oracle query - Selecting unique row number based on order of another columnOracle查询 - 根据另一列的顺序选择唯一的行号
【发布时间】:2021-06-06 14:53:30
【问题描述】:

我正在尝试找到使用两列进行查询的最佳方法,一列是数字,顺序是日期:

按日期列进行选择和排序。

表 1

col1 (NUMBER) col2 (DATE)
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 (NUMBER) col2 (DATE)
1 02/2019
2 02/2019
3 02/2019
4 03/2019
2 04/2019
3 05/2019

但我希望过滤器仅限于这样的顺序 col1 值:

col1 (NUMBER) col2 (DATE)
1 02/2019
2 02/2019
3 02/2019
4 03/2019

忽略将在“下一批”中出现的值,并且不会冒重复 col1 值的风险,或者得到 col2 值大于先前结果的 col1 值。

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

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2018-01-31
      • 2015-11-25
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多