Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: row_number: ERROR: column "rn" does not exist

Tags:

postgresql

I need help with my query. I want to add a row_number to partition my fields, but I get the error: ERROR: column "rn" does not exist LINE 22: and rn <= 3
Do you find something strange in my query? Thanks a lot!

with location as 
(select location, topcount
from pr.rankinglist_location
where topcount = 3
or (topcount = 10 and population_all > 150000)
or topcount = 25)

select store_displayname as restaurant_name,
    street,
    street_no,
    zipcode,
    city, 
    topcount,
    ROW_NUMBER() OVER (PARTITION BY city
                              ORDER BY rposition DESC) rn,
    store_id as store_id
from pr.rankinglist_store s
join
location m on m.location = s.city 
where 
statkey = '2015' 
and
topcount = 3
and rn <= 3
group by 1, 2, 3, 4, 5, 6, 7, 8
order by rposition
like image 513
Athanasia Ntalla Avatar asked Apr 26 '26 18:04

Athanasia Ntalla


1 Answers

Aliases are not accessible, and window functions are not allowed in WHERE clause. Use a derived table:

...
select *
from (
    select 
        store_displayname as restaurant_name,
        street,
        street_no,
        zipcode,
        city, 
        topcount,
        ROW_NUMBER() OVER (PARTITION BY city
                          ORDER BY rposition DESC) rn,
        store_id as store_id
    from pr.rankinglist_store s
    join location m on m.location = s.city 
    where statkey = '2015' 
    and topcount = 3
    group by 1, 2, 3, 4, 5, 6, 7, 8
    order by rposition
    ) sub
where rn <= 3;
like image 125
klin Avatar answered Apr 30 '26 02:04

klin