找出sql中不断增加的子序列

时间:2017-05-18 17:15:00

标签: sql postgresql sequence

假设我有x和y值的表,其中y是有序的DESC,例如

recInstance

现在我想找到从第一个值开始增加x的子序列 即我希望获得以下输出,其中x遵循递增的顺序。

  x  |  y  
-----+-----
  94 | 985
  73 | 940
 469 | 865
 115 | 864
 366 | 862
 525 | 842
 448 | 837
 318 | 832
 507 | 826
 244 | 758
 217 | 741
 207 | 732
  54 | 688
 426 | 605
 108 | 604
 610 | 587
 142 | 581
 765 | 579
 102 | 572
 512 | 552
 836 | 540

这可以通过sql查询还是我需要在更新最大值时使用plpgsql函数和循环?

3 个答案:

答案 0 :(得分:1)

您可以使用lead()解决原始问题,假设您有一个指定排序的列:

select x.*
from (select t.*, sum( (next_x < x)::int) over (order by orderingcol) as grp
      from (select t.*, lead(x) over (order by orderingcol) as next_x
            from t
           ) t
     ) t
where grp = 0;

编辑:

以上将省略最后一个元素。我知道我应该用lag()编写,然后用lead()重新编写它。所以,更好的版本是:

select x.*
from (select t.*, sum( case when x < prev_x then 1 else 0 end ) over (order by orderingcol) as grp
      from (select t.*, lag(x) over (order by orderingcol) as prev_x
            from t
           ) t
     ) t
where grp = 0;

答案 1 :(得分:1)

您可以使用max窗口功能跟踪运行的最大值。基本上你的输出要求。

select distinct max(val) over(order by id) --replace id with your ordering column
from t

编辑:在OP编辑问题后

select x,y 
from (select distinct y,x,max(x) over(order by y desc) running_x_max
      from t
     ) t
where running_x_max=x
order by y desc

答案 2 :(得分:1)

假设给定的顺序你有一个名为id的列,你可以使用窗口函数max和窗口规范:

select *
from (
    select t.*,
        case when x >= max(x) over (
                    order by id rows between unbounded preceding and current row
                    ) then 1 else 0 end as flag
    from t
    ) t
where flag = 1;-- or 0 if you want to get the remaining ones.

Demo

Demo for "bonus" one