sql - 在 Postgres 中获取具有复杂分区的重复值的连续计数
问题描述
给定一组 3 列(蓝色列:学生、学期、年级),我需要使用 Postgres 中的查询计算每个学生连续多少个学期具有相同的成绩(绿色列)。
(连续第一个学期平均为 8:consec = 1。第二个 consec 学期平均为 8:consec = 2...)
样本数据小提琴:https ://www.db-fiddle.com/f/v31a5Bpere26tXQb5L1fFJ/0
预期结果:
我试过使用
ROW_NUMBER() OVER(partition by student)
ROW_NUMBER() OVER(partition by avg_grade)
ROW_NUMBER() OVER(partition by student, avg_grade)
ROW_NUMBER() OVER(partition by student, semester)
但以上都没有得到预期的结果。
非常感谢你的帮助!
解决方案
这是一种间隙和孤岛问题。最简单的方法可能是使用每个年级和学期的序列之间的差异来定义组。然后使用row_number()
更多时间:
select g.*,
row_number() over (partition by student, avg_grade, semester - seqnum order by semester) as consec_avg
from (select g.*,
row_number() over (partition by student, avg_grade order by semester) as seqnum
from grades
) g;
这是一个 db<>fiddle。
推荐阅读
- javascript - 如何根据 JS/Jquery 中的状态对数据进行分组
- file-upload - 如何在codeigniter 3上上传图像文件?
- javascript - JS - 将活动类添加到与悬停元素具有相同数据属性的元素
- assembly - 为什么不允许使用 THUMB 指令“mov r0,#0”?
- javascript - 将 ngModel 而不是 value 绑定到用于货币输入的自定义 Angular 指令
- python - 从本地机器访问 linux 服务器中的 django 应用程序
- python - 如何将键盘输入变成函数以减少混乱
- swift - 在 SwiftUI 中的 Picker 之外使用 Picker 选择值
- line - Pine脚本从if语句中删除旧行?
- javascript - 如何从 HTML 中选择要在 Javascript 中使用的特定用户输入