Hellmuth Vargas escribió:

> SELECT *,
>         array_agg(x) OVER () as todos,
> array_agg(x) OVER (ORDER BY x) as order_asc,
>         array_agg(x) OVER (ORDER BY x DESC) as order_desc,
>         last_value(x) OVER (ORDER BY x)
>        FROM generate_series(1, 5) AS x order by 1;
> 
> cuyos resultados son:
> 
>  x |    todos    |  order_asc   |  order_desc  | last_value
> ---+-------------+-------------+-------------+------------
>  1 | {1,2,3,4,5} | {1}         | {5,4,3,2,1} |          1
>  2 | {1,2,3,4,5} | {1,2}       | {5,4,3,2}   |          2
>  3 | {1,2,3,4,5} | {1,2,3}     | {5,4,3}     |          3
>  4 | {1,2,3,4,5} | {1,2,3,4}   | {5,4}       |          4
>  5 | {1,2,3,4,5} | {1,2,3,4,5} | {5}         |          5
> (5 rows)
> 
> 
> Y la verdad no entiendo la lógica del 'filtrado' que hace el order by
> (ASC/DESC). Gracias Lista

No es el ASC/DESC que hace filtrado.  Y en realidad no se hace ningún filtrado;
lo que se hace es definir el "frame".  Como no lo especificas, la documentación
indica cuál es la definición por omisión:

        The default framing option is RANGE UNBOUNDED PRECEDING, which is the
        same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; it sets the
        frame to be all rows from the partition start up through the current
        row's last peer (a row that ORDER BY considers equivalent to the
        current row, or all rows if there is no ORDER BY).
https://www.postgresql.org/docs/10/static/sql-select.html

es decir, en cada registro, el frame es "todos los registros que vienen
antes del registro actual (UNBOUNDED PRECEDING), y hasta el registro
actual (CURRENT ROW)".  Con el ASC/DESC del order by, cambias la
definición de cuáles registros vienen "antes".

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Reply via email to