2

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
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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.