前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >row_number() OVER (PARTITION BY COL1 ORDER BY COL2)「建议收藏」

row_number() OVER (PARTITION BY COL1 ORDER BY COL2)「建议收藏」

作者头像
全栈程序员站长
发布2022-07-07 20:38:59
2730
发布2022-07-07 20:38:59
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君。

row_number() OVER (PARTITION BY COL1 ORDER BY COL2) –表示依据COL1分组,在分组内部依据 COL2排序。而此函数返回的值就表示每组内部排序后的顺序编号(组内连续的唯一的)

代码语言:javascript
复制
create table student (id int ,classes int ,score int);
insert into student values(1,1,89);
insert into student values(2,1,90);
insert into student values(3,1,76);
insert into student values(4,2,69);
insert into student values(5,2,79);
insert into student values(6,2,95);
insert into student values(7,3,80);
insert into student values(8,3,85);
insert into student values(9,3,79);
commit;
代码语言:javascript
复制
select t.* from student t;

–数据显示为 id classes score ————————————————————- 1 1 89 2 1 90 3 1 76 4 2 69 5 2 79 6 2 95 7 3 80 8 3 85 9 3 79

–需求:依据班级分组,显示每一个班的英语成绩排名

–预期结果:

id classes score rank ———– ———– ————————————— 3 1 76 1 1 1 89 2 2 1 90 3 4 2 69 1 5 2 79 2 6 2 95 3 9 3 79 1 7 3 80 2 8 3 85 3

–SQL脚本:

代码语言:javascript
复制
SELECT *, Row_Number() OVER (partition by classes ORDER BY score desc) rank FROM student;

–查询t_test表中,callid字段没有反复过的数据,效率高过group by having count

代码语言:javascript
复制
select t.*, t.rowid
  from t_test t
 where t.rowid not in (select rid
                         from (select t2.rowid rid,
                                      row_number() over(partition by t2.callid order by t2.rowid desc) m
                                 from t_test t2)
                        where m <> 1)
   and t.rowid not in (select rid
                         from (select t2.rowid rid,
                                      row_number() over(partition by t2.callid order by t2.rowid asc) m
                                 from t_test t2)
                        where m <> 1);

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116265.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档