SQL Rank 条件
Posted
技术标签:
【中文标题】SQL Rank 条件【英文标题】:SQL Rank condition 【发布时间】:2020-03-14 23:18:33 【问题描述】:我正在运行此代码来选择 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
【问题讨论】:
【参考方案1】:将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
【讨论】:
以上是关于SQL Rank 条件的主要内容,如果未能解决你的问题,请参考以下文章
sql 中 rank() over,dense_rank(),row_number() 的区别
R语言使用wilcox.test函数进行两组数据的Wilcoxon符号秩检验wilcox.test函数添加paired参数则为Wilcoxon signed rank,当t检验需要的正态性条件不满足