I am using Posgresql and I want to write a query to perform the following. Suppose the table is like this:
id section views
1 1 10
2 2 8
3 1 20
4 1 21
5 2 0
I want to count each row that has the same "section" value (ordered by "views") like this:
id section views contador
4 1 21 1 //section 1 contador 1
3 1 20 2 //section 1 contador 2 ...
1 1 10 3
2 2 8 1 //section 2 contador 1
5 2 0 2 //section 2 contador 2
Evan Carroll
65.8k50 gold badges263 silver badges520 bronze badges
1 Answer 1
You need to use a Window Function like row_number()
SELECT
id,
section,
views,
row_number() OVER (PARTITION BY section ORDER BY views DESC)
FROM table;
answered Jul 20, 2018 at 19:43
Evan Carroll
65.8k50 gold badges263 silver badges520 bronze badges
lang-sql