Answer the question
In order to leave comments, you need to log in
How to filter the result of an OVER query with row_number function?
There is a table of users, which, when displayed, is sorted by User.timestamp.
show "your number in the list". The current solution works, but I also need to filter by role_id==current_user.role_id of the user.
Algorithm:
1. make a selection of all records sorted by User.timestamp,
2. We are looking for a record with the current user_id
It is not possible to insert a filter by role in the first stage.
query = db.session.query(
User.id,
over(
func.row_number(),
order_by=User.timestamp
)
).filter(User.id == current_user.id).first()
SELECT "user".id AS user_id,"user".role_id as role_id, row_number()
OVER (ORDER BY "user".timestamp )
AS anon_1 FROM "user" WHERE "user".id = {0}
Answer the question
In order to leave comments, you need to log in
As it turned out, the request was incorrect
WITH UsersRez AS
(
SELECT "user".role_id as role_id, "user".id as user_id, ROW_NUMBER()
OVER (ORDER BY timestamp DESC) AS RowNumber
FROM "user" where role_id={0}
)
SELECT RowNumber,user_id
FROM UsersRez
WHERE user_id = {1}
.format(current_user.role.id, current_user.id) Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question