首页 > 解决方案 > 在 PostgreSQL 中选择不同的窗口函数

问题描述

我有一个如下的数据表:

如何在 10 步滚动窗口中为每个纵向距离选择不同的连续性?

理想情况下,我希望理想输出列中的结果是数组。

谢谢。 在此处输入图像描述

标签: sqlpostgresqlwindow-functionsrolling-computation

解决方案


一种方法使用数组:

select t.*,
       (select count(distinct c) from unnest(ar) c) as num_distinct
from (select t.*,
             array_agg(continuity) over (order by distance rows between 9 preceding and current row) ar
      from t
     ) t;

编辑:

或者,如果您想要这些值,请将它们聚合:

select t.*,
       (select array_agg(distinct c) from unnest(ar) c) as num_distinct
from (select t.*,
             array_agg(continuity) over (order by distance rows between 9 preceding and current row) ar
      from t
     ) t;

推荐阅读