M
M
manavalit2020-04-28 13:18:06
PostgreSQL
manavalit, 2020-04-28 13:18:06

How to get row number + sorted by one column?

I am writing a telegram bot like a quiz. I have a PostgreSQL table which has id (SERIAL), user_id of the telegram user, the number of answers in total, correct and incorrect. I need to show the user his place in the general list by the number of correct answers. But I don't know how to implement it. I tried making a request like this:

SELECT user_id, row_number() OVER(ORDER BY right DESC) as number FROM users

But it gives out the entire table, and I only need one user at a time. I have also tried doing this:
SELECT user_id, row_number() OVER(ORDER BY right DESC) as number FROM users WHERE user_id=%s

But it always gives the number 1, because it looks for the number of correct answers only for this user.
It turns out that we must first sort the table and number it, and then get the row number in which user_id=%s
Do not tell me how to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-stream, 2020-04-28
@manavalit

Simplified:

select * from (select ..... ) as abc where abc.user=xxx

that is, the inner query will "number" the data as it should, and the outer query will select only the necessary positions from this numbered one.
ps but in general "user's place" - more suggests RANK ()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question