Postgres Sql 如何以正确的顺序获得此排名顺序

Postgres Sql How can I get this ranking order with correct sequence

我有 2 Tables ProfilesCircles。配置文件 table 有一个名为 points 的列。我正在尝试做一个排名,本质上是让所有你关注的人根据分数从上到下对他们进行排名。这行得通,我的问题是我还想将执行以下操作的实际人员包括在该级别中。我 table 的这些照片应该可以说明

圈子 table 拥有 my_id 的人正在关注 other_id

个人资料Table

下面我的 ID 是 57,我正在关注 59,下面是我的查询,输出是 14,因为这是用户 ID 59 拥有的点数。我还想在下面的查询中包含我自己的记录,这样我就可以看到我与我关注的人的排名。查询应该 return 14 和 3 而不是 14 now 。任何建议都会很棒。

   Select p.points from profiles p
     join circles c on p.ID = c.other_id
     where c.my_id=57 order by p.points desc

我们可以尝试在 CTE 中引入计算列,以跟踪给定用户是否与进行排名的用户相对应。然后,select 来自该 CTE 并使用计算列进行排序。

WITH cte AS (
    SELECT p.ID, p.points,
        CASE WHEN c.my_id = 57 THEN 0 ELSE 1 END AS position
    FROM profiles p
    INNER JOIN circles c
        ON p.ID = c.other_id
)

SELECT ID, points
FROM cte
ORDER BY position, points DESC;

这里的一个极端情况是执行排名的用户不会出现在下面的列表中。如果您真的希望排名用户同时出现在列表中和顶部,那么您将不得不使用联合:

SELECT p.ID, p.points, 0 AS position
FROM profiles p
INNER JOIN circles c
    ON p.ID = c.other_id
WHERE c.my_id = 57
UNION ALL
SELECT p.ID, p.points, 1
FROM profiles p
INNER JOIN circles c
    ON p.ID = c.other_id
ORDER BY
    3, 2 DESC;

如果我没理解错的话,大概是这样的

select (select points from profiles where id = c.my_id ) my_points, 
  (select points from profiles where id = c.other_id) other_points
from circles c
where my_id = 57
order by 1 desc,2 desc

注意事项:
1) 假设在给定条件下圆圈中的线数相对较少。如果不是这种情况,最好通过加入个人资料来添加信息 table
2) 我猜你想要 other_id 的分数,而不是排名