V
V
Vladimir Abiduev2015-07-25 18:18:51
PostgreSQL
Vladimir Abiduev, 2015-07-25 18:18:51

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}


Spoke funcfilter, but he is in some incomprehensible state

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Abiduev, 2015-07-26
@gunlinux

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)
The result is simulating the behavior of the same freelansim, you are the 1052nd freelancer on the list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question