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

sum over unique Weights of a job partition by sub id

我有一个 table 有两个 IDS。第一个产品 ID 和第二个作业 ID。每个工作都有不同的操作。 Dach操作有权重

示例table:

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.   |

每个工作的OPs需要的Wrights总和,但是在上一份工作中完成的OPs不应该在第二份工作中考虑。

必填Table

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 逻辑的帮助

这有点难以理解。您似乎想要第一个 OP 值的累加和。对于给定的 jobid/weight.

,此累积总和是 "spread" 通过行

您可以使用 window 函数来做到这一点。最简单的方法使用 range between windowing 子句:

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;