按子ID对作业分区的唯一权重求和

时间:2017-08-04 16:00:29

标签: sql hana

我有一张桌子有两个IDS。第一个产品ID和第二个作业ID。每个工作都有不同的操作。达赫行动有重量。

示例表:

ProductID| JobID     | OP  | weight    | 
---------+-----------+-----+-----------+
     1.  |     1.     | M.    |   0.   |
     1.  |     1.     | P.    |   1.   |
     1.  |     1.     | L.    |   3.   |
     1.  |     1.     | K.    |   0.   |
---------+------------+-------+--------+---- 
     1.  |     2.     | P.    |   1.   |
     1.  |     2.     | W.    |   0.   |
     1.  |     2.     | N.    |   2.   |
---------+------------+-------+--------+---- 
     1.  |     3.     | P.    |   1.   |
     1.  |     3.     | L.    |   3.   |
---------+------------+-------+--------+---- 
     1.  |     4.     | M.    |   0.   |
     1.  |     4.     | O.    |   1.   |
     1.  |     4.     | L.    |   0.   |

每个工作都需要VS的权利,但在以前的工作中完成的OP不应该在第二份工作中考虑。

必填表

ProductID   | JobID | OP  | sum | 
------------+-------+-----+-----+
     1.     |     1.| M.  |   4.|
     1.     |     1.| P.  |   4.|
     1.     |     1.| L.  |   4.|
     1.     |     1.| K.  |   4.|
------------+-------+-----+-----+---- 
     1.     |     2.| P.  |   6.|
     1.     |     2.| W.  |   6.|
     1.     |     2.| N.  |   6.|
------------+-------+-----+-----+ 
     1.     |     3.| P.  |  9. |
     1.     |     3.| L.  |  9. |
------------+-------+-----+-----+ 
     1.     |     4.| M.  |  10.|
     1.     |     4.| O.  |  10.|
     1.     |     4.| L.  |  10.|

一旦操作完成,他们的重量不应该在下一个但是总和中被考虑。

Sum(i)+sum(i+1)-sum(Weights of OPs previously done!)

我需要SQL逻辑的帮助

1 个答案:

答案 0 :(得分:3)

这有点难以理解。您似乎想要第一个OP值的累积和。然后,对于给定的jobid /权重,该累积总和将通过行“展开”。

您可以使用窗口功能执行此操作。最简单的方法使用range between窗口子句:

select t.*,
       sum(case when seqnum = 1 then weight else 0 end) over
           (order by productid, jobid
            range between unbounded preceding and current row
           ) as new_weight
from (select t.*,
             row_number() over (partition by op order by productid, jobid) as seqnum
      from t
     ) t;

并非所有数据库都支持range between。假设weight永远不会为负数,您只需计算每个productid / jobid分组的最大值:

select t.*, max(tmp_weight) over (partition by productid, jobid) as new_weight
from (select t.*,
             sum(case when seqnum = 1 then weight else 0 end) over
                 (order by productid, jobid) as tmp_weight
      from (select t.*,
                   row_number() over (partition by op order by productid, jobid) as seqnum
            from t
           ) t
     ) t;