首页 > 解决方案 > 比较来自特定列分组的数据并根据条件更新

问题描述

我有一个具有以下结构的表:

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 字段,它只是为了更清楚地说明。

标签: sqloracle

解决方案


使用分析函数确定上一年是否有分数,如果有,将其添加到 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;

推荐阅读