在sql中查找递增子序列

在sql中查找递增子序列,sql,postgresql,sequence,Sql,Postgresql,Sequence,例如,假设我有一个x和y值表,其中y是ordered DESC 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 |

例如,假设我有一个x和y值表,其中y是ordered DESC

  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
现在我想从第一个值开始求x的递增子序列 i、 e.我希望获得以下输出,其中x遵循递增顺序

  x  |  y  
-----+-----
  94 | 985
 469 | 865
 525 | 842
 610 | 587
 765 | 579
 836 | 540

这是通过sql查询实现的,还是在更新最大值时需要使用plpgsql函数和循环

您可以使用
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;

您可以使用
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;

您可以使用
max
窗口功能跟踪正在运行的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

您可以使用
max
窗口功能跟踪正在运行的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

假设对于给定的顺序,您有一个名为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.

假设对于给定的顺序,您有一个名为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.

删除奖金问题并将其作为新问题发布。此问题没有解决方案。SQL表表示无序集。除非列指定排序,否则没有第一行。好的,我现在将进行一些编辑删除奖金问题并将其作为新问题发布。这个问题没有解决方案。SQL表表示无序集。除非列指定了顺序,否则没有第一行。好的,我现在会做一些编辑。我不知道max函数能发挥这么大的魔力,非常感谢!我不知道max function能表演这么神奇的表演,非常感谢!谢谢你的回答。但是有一个小缺点,数字不一定只跳过一行。谢谢你的回答。但是有一个小缺点,数字不一定只跳过一行。谢谢你的回答。但我不明白什么是无界的前一行和当前行。@Peter这是一种为窗口函数定义窗口起点和终点的机制,如max、sum、count等。谢谢您的回答。但我不明白什么是无界的前一行和当前行。@Peter这是一种为窗口函数定义窗口起点和终点的机制,如max、sum、count等。