SQL排名条件

问题描述 投票:2回答:1

我正在运行此代码来选择sql中每个数据库的等级。但是,我没有得到想要的结果。

数据库:代码:

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
sql postgresql window-functions rank
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
© www.soinside.com 2019 - 2024. All rights reserved.