A
A
Alex Fedorov2022-02-14 15:47:58
PostgreSQL
Alex Fedorov, 2022-02-14 15:47:58

Display the top 10 users by rating + the user himself?

I have a task to write a query:

There is a table with users where they each have a rating, you need to make such a query to display the TOP 10 users FOR THE WHOLE USERS table + at the end of the table, regardless of its rating and position of the row with the data of the user who views the feed.

That is,
1
2
3
4
5
6
7
8
9
10
*here is the data of the user who is viewing the database. It can be the first, and the seventh, and at least the last, but at the end I have to at least somehow display a line with its data.

Please help me, how can this be done?

SELECT top.*
FROM(
    SELECT u.avatar_path AS "Avatar", u.rating AS "Rating"
    FROM users AS u 
    WHERE u.id IN(
        SELECT u.id
        FROM users AS u
    )
)AS top
ORDER BY top."Rating" DESC
LIMIT 10

UNION 
SELECT user.*
FROM(
    SELECT u.avatar_path AS "Avatar", u.rating AS "Rating"
    FROM users AS u 
    WHERE u.id = 1
) AS user;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrColdCoffee, 2022-02-14
@robben_55

SELECT *
FROM(
    SELECT u.avatar_path AS "Avatar", u.rating AS "Rating"
    FROM users AS u ORDER BY u.rating DESC LIMIT 10 
)AS top 
UNION ALL
    SELECT u2.avatar_path AS "Avatar", u2.rating AS "Rating"
    FROM users AS u2 
    WHERE u2.id = 1

(SELECT u.avatar_path AS "Avatar", u.rating AS "Rating" FROM users AS u order by u.rating desc limit 10)
UNION ALL
(SELECT u2.avatar_path AS "Avatar", u2.rating AS "Rating" FROM users AS u2 WHERE u2.id = 1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question