sql >> Base de Datos >  >> RDS >> PostgreSQL

Contar filas en partición con Ordenar por

Cuando agrega un order by a un agregado utilizado como función de ventana, ese agregado se convierte en un "recuento continuo" (o cualquier agregado que use).

El count(*) devolverá el número de filas hasta el "actual" según el orden especificado.

La siguiente consulta muestra los diferentes resultados para los agregados usados ​​con un order by . Con sum() en lugar de count() es un poco más fácil de ver (en mi opinión).

with test (id, num, x) as (
  values 
    (1, 4, 1),
    (2, 4, 1),
    (3, 5, 2),
    (4, 6, 2)
)
select id, 
       num,
       x,
       count(*) over () as total_rows, 
       count(*) over (order by id) as rows_upto,
       count(*) over (partition by x order by id) as rows_per_x,
       sum(num) over (partition by x) as total_for_x,
       sum(num) over (order by id) as sum_upto,
       sum(num) over (partition by x order by id) as sum_for_x_upto
from test;

dará como resultado:

id | num | x | total_rows | rows_upto | rows_per_x | total_for_x | sum_upto | sum_for_x_upto
---+-----+---+------------+-----------+------------+-------------+----------+---------------
 1 |   4 | 1 |          4 |         1 |          1 |           8 |        4 |              4
 2 |   4 | 1 |          4 |         2 |          2 |           8 |        8 |              8
 3 |   5 | 2 |          4 |         3 |          1 |          11 |       13 |              5
 4 |   6 | 2 |          4 |         4 |          2 |          11 |       19 |             11

Hay más ejemplos en el manual de Postgres