根据另一列的条件值添加不同的列值

时间:2020-11-04 21:41:07

标签: sql oracle

我从SQL查询中获得以下输出:

Project_Manager_ID   PROject_Rank  On_boarding_Gap    Project_Gap    End_Gap
101                   1                   2                 3           0.833
101                   2                   7                 1           3.4
101                   3                   0                 -3           0
101                   4                   3                 1            1.2
102                   1                   -1                 0            1
102                   2                    2                 3            2
102                   3                    5                 2           -3

这是业务规则:

当等级= 1时,则On_boarding_gap

当等级> 1和等级<(根据Project_Manager_ID的最大(等级)组)然后是Project_gap

当根据Project_Manager_ID排名=最大(排名)分组时,则End_Gap

添加所有这些不同的差距,并找到每个Project_Manager_ID的差距总值。忽略所有负值。 因此,在上面的示例中, Project_Manager_ID = 101

On_boarding_gap = 2

Project_gap = 1&-3 = 1(忽略-3值)

End_Gap = 1.2

总差距为(2 + 1 +1.2)= 4.2。

对于Project_Manager_ID = 102

On_boarding_gap = -1 = 0(忽略-1值)

Project_gap = 3

End_Gap = -3 = 0(忽略-3值)

总差距为(0+ 3 + 0)= 3

我不确定如何为此编写查询。

1 个答案:

答案 0 :(得分:0)

嗯。 。 。 case表达式和窗口函数可为您提供每一行的空白:

select t.*,
       (case when project_rank = 1
             then on_boarding_gap
             when project_rank < max(project_rank) over (partition by Project_Manager_ID)
             then Project_gap
             else End_Gap
        end) as imputed_gap
from t;

然后聚合:

select Project_Manager_ID, sum(imputed_gap)
from (select t.*,
             (case when project_rank = 1
                   then on_boarding_gap
                   when project_rank < max(project_rank) over (partition by Project_Manager_ID)
                   then Project_gap
                   else End_Gap
              end) as imputed_gap
      from t
     ) t
where imputed_gap >= 0
group by Project_Manager_ID