sql - 比较来自特定列分组的数据并根据条件更新
问题描述
我有一个具有以下结构的表:
Employee Project Task Accomplishment Score Year
John A 1 5 60 2016
John A 1 6 40 2018
John A 2 3 30 2016
Simon B 2 0 30 2017
Simon B 2 4 30 2019
David C 1 3 20 2015
David C 1 2 40 2016
David C 3 0 25 2017
David C 3 5 35 2017
我想使用上表的 Oracle SQLout 创建一个视图,如下所示:
Employee Project Task Accomplishment Score Year UpdateScore Comment
John A 1 5 60 2016 60
John A 1 6 40 2018 100 (=60+40)
John A 2 3 30 2016 30
Simon B 2 0 30 2017 30
Simon B 2 4 40 2019 40 (no update because Accomplishement was 0)
David C 1 3 20 2015 20
David C 1 2 40 2016 60 (=20+40)
David C 3 0 25 2017 25
David C 3 5 35 2017 35 (no update because Accomplishement was 0)
分组是:员工-项目-任务。
UpdateScore 列的规则:
如果对于特定的员工-项目-任务组,上一年的成就列值大于 0,则将上一年的分数添加到同一员工-项目-任务组的最近一年。
例如:John-A-1 是一个不同于 John-A-2 的组。所以我们可以看到 John-A-1 在 2016 年的成绩是 5(大于 0),所以我们将 2016 年的分数与 John-A-1 的 2018 年分数相加,更新后的分数变为 100 .
对于 Simon-B-2,成绩为 0,因此 Simon-B-2 的 2019 年将没有更新。
注意:我不需要 Comment 字段,它只是为了更清楚地说明。
解决方案
使用分析函数确定上一年是否有分数,如果有,将其添加到 UpdatedScore。
select Employee, Project, Task, Accomplishment, Score, Year,
case when lag(Year) over (partition by Employee, Project order by Year) = Year - 1
then lag(Score) over (partition by Employee, Project order by Year)
else 0
end + Score as UpdatedScore
from EmployeeScore;
推荐阅读
- java - 将参数传递给 gradle 构建脚本
- php - 不按应有的方式将数据插入数据库
- python - 是否可以使用 NumPy 或 Python 中的其他包获得保留的特殊数量的双精度二进制浮点数
- java - 来自 java 的存储过程调用抛出“游标状态无效”错误
- jquery - jQuery File Upload blueimpl 浏览器冻结
- python - 如何在 wxpython 上实现图像?
- javascript - 如何解决 Safari 上 angularjs 的问题?
- android - RxBinding 或 RxAndroid
- wordpress - 如何在特定页面上显示运输方式选择?
- c# - 如何在同一端口上运行带有 .net framework 4.7.1 WebAPI 的 Angular Web 应用程序?