SQL排名条件

SQL Rank condition

我运行此代码selectsql中每个数据库的排名。但是,我没有得到我想要的结果。

数据库: 代码:

SELECT user_id,country,city,institute,  
RANK () OVER (PARTITION BY country ORDER BY up_vote+down_vote DESC) country_rank,
RANK() OVER (PARTITION BY city ORDER BY up_vote+down_vote DESC) city_rank,
RANK() OVER (PARTITION BY institute ORDER BY up_vote+down_vote DESC) institute_rank
FROM Users ;
FROM Users;
 user_id | country |  city   |      institute       | country_rank | city_rank | institute_rank
---------+---------+---------+----------------------+--------------+-----------+----------------
      17 | Canada  | Toronto | University of Ottawa |            1 |         1 |              1
      18 | Canada  | Ottawa  | University of Ottawa |            2 |         1 |              2
      16 | test123 | test123 | test123              |            1 |         1 |              1

我只想得到 user_id=18 所以我加了 WHERE user_id=18

但是,我的结果是这样

 user_id | country |  city  |      institute       | country_rank | city_rank | institute_rank
---------+---------+--------+----------------------+--------------+-----------+----------------
      18 | Canada  | Ottawa | University of Ottawa |            1 |         1 |              1

我想要的结果

 user_id | country |  city  |      institute       | country_rank | city_rank | institute_rank
---------+---------+--------+----------------------+--------------+-----------+----------------
      18 | Canada  | Ottawa | University of Ottawa |            2 |         1 |              2

直接在查询中放置 where 子句会在排名函数有机会执行之前从数据集中删除行。只剩下一行,所以在每个分区中都排在第一位。

您需要在子查询中排名,然后在外部查询中过滤:

SELECT *
FROM (
    SELECT 
        user_id,
        country,
        city,
        institute,  
        RANK() OVER (PARTITION BY country ORDER BY up_vote+down_vote DESC) country_rank,
        RANK() OVER (PARTITION BY city ORDER BY up_vote+down_vote DESC) city_rank,
        RANK() OVER (PARTITION BY institute ORDER BY up_vote+down_vote DESC) institute_rank
    FROM Users
) t
WHERE user_id = 18