Skip to content
Advertisement

select distinct window function in PostgreSQL

I have a data table like the following:

How do you select the distinct continuities for each Longitudinal distance in a 10-step rolling window?

Ideally, I’d want something in the Ideal output column in which the results are arrays.

Thanks. enter image description here

Advertisement

Answer

One method uses arrays:

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;

EDIT:

Or, if you want the values, aggregate them:

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;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement