I have a query where I am ranking the returned rows (related question). What I would like to be able to do is reverse the rank, and set the new_rank accordingly. Lets assume I have 999
entries.
For instance if I have this query:
with persondata as (
SELECT firstname,
lastname,
year,
personid,
((SELECT COALESCE(SUM(thevalue),0)
FROM assets
WHERE personidref = w.personid AND year = w.year)
- (SELECT COALESCE(SUM(amount),0)
FROM liabilities
WHERE personidref = w.personid AND year = w.year)) as worth,
row_number() over(ORDER BY w.worth DESC) as new_rank,
visible
FROM members w
WHERE year = 2014
AND visible = 1
ORDER BY worth ASC LIMIT 5
)
select row_number() over (order by worth DESC) as rank,
*
from persondata
This rightly returns the bottom 5 in the desired order see below:
rank | firstname | lastname | worth | new_rank
------+-----------+-------------------+----------+----------
1 | Peter | Griffin | -520000 | 145
2 | Steve | Moffat | -530000 | 519
3 | Gregory | Peck | -540000 | 131
4 | Ruben | Mumbles | -550000 | 130
5 | Ricky | Swiss | -560000 | 120
Is there a way to incorporate the row_count
and subtract current row count? Or set a counter to be used temporarily, that is set to row count then decrement?
Final desired result:
rank | firstname | lastname | worth | new_rank
------+-----------+-------------------+----------+----------
997 | Peter | Griffin | -520000 | 145
996 | Steve | Moffat | -530000 | 519
997 | Gregory | Peck | -540000 | 131
998 | Ruben | Mumbles | -550000 | 130
999 | Ricky | Swiss | -560000 | 120
I haven't been able to find anything regarding this implementation on using row_number
.