Postgresql – How to count rows based on a column value

postgresqlwindow functions

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

Best Answer

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;