2017-08-04 52 views
0

我有一個表有兩個IDS。第一個產品ID和第二個工作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. | 

需要資金萊特兄弟爲有機磷農藥的每一項工作,但在以前的工作做了有機磷農藥不應該在第二個作業被馮考慮。

所需的表

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

一旦操作完成後,其weigts不應該在未來,但總和considred。

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

我需要與SQL邏輯

回答

3

這是一個有點難以遵循幫助。你似乎想要第一個OP值的累計和。這個累積總和然後通過行「傳播」給定工作/重量。

你可以用窗口函數來做到這一點。最簡單的方法是使用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; 
+0

非常感謝! (select t。*, row_number()over(partition))上的select [.t, sum(case when seqnum = 1 then then weight 0 end)按照產品編號,jobid),序號爲 ,來自t ' – Sai