Search code examples
sqlpostgresqlwindow-functionspartitioning

Reverse order in partitions


I have this query

select
*,
row_number() over w,
sum(satisfied::integer) over w,
round(avg(satisfied::integer) over w, 3)*10
from compositions_rating
window w as (partition by user_id order by rating_date asc)

That gives me this (took part of partitions where user_id = 1)partition

But also I want to have make query with reversed order in partition like this partition 2

May be this is silly question, but how can I do this?

UPD: My best attempt was this

select
*,
row_number() over w,
sum(satisfied::integer) over w,
round(avg(satisfied::integer) over w, 3)*10
from compositions_rating
window w as (partition by user_id order by rating_date desc rows between current row and UNBOUNDED following)

But row numbers are going in normal order in this case, as they were supposed toenter image description here

UPD2: What you get if ordering after partitions made order


Solution

  • For me it looks like you already have the expected result but simply want to change the complete order afterwards... So, doesn't this solve you problem?

    SELECT
        *
    FROM (
       -- <your query>
    ) s
    ORDER BY user_id, rating_date DESC