2014-11-25 33 views
2

更新表中的記錄可以說我有一個表TBL(代表工作簡單timelogs對不同的客戶製造),累計結果

五列 編號:詮釋 TimeUse:浮 IdCustomer:整數 創建:日期時間 TimeCalc:浮

我有一些在這個表中的記錄,(TimeCalc被初始化爲值= 0)

我想我的SQL做的是:

當TimeUse用於在特定客戶的所有前述記錄累積到一個值< 10然後在TimeCalc的值應爲0時TimeUse用於在特定客戶的所有前述記錄累積到的值> = 10

則TimeCalc中的值應該= TimeUse的記錄...

我已經搞亂了Case例程與子查詢,但不能得到它的工作。

BEFORE 
    Id  TimeUse  IdCustomer  Created  TimeCalc 
    1   2    1     14/09/09  0 
    2   5    2     14/09/10  0 
    3   2    1     14/09/11  0 
    4   5    2     14/09/12  0 
    5   4    1     14/09/13  0 
    6   2    2     14/09/14  0 
    7   4    1     14/09/15  0 
    8   1    1     14/09/16  0 
    9   3    2     14/09/17  0 
    10  2    1     14/09/18  0 
    11  4    2     14/09/19  0 



AFTER 
    Id  TimeUse  IdCustomer  Created  TimeCalc 
    1   2    1     14/09/09  0 
    2   5    2     14/09/10  0 
    3   2    1     14/09/11  0 
    4   5    2     14/09/12  0 
    5   4    1     14/09/13  0 
    6   2    2     14/09/14  2 
    7   4    1     14/09/15  0 
    8   1    1     14/09/16  1 
    9   3    2     14/09/17  3 
    10  2    1     14/09/18  2 
    11  4    2     14/09/19  4 

這可以在SQL更新中解決嗎?

回答

2

在SQL Server 2012+,你可以用一個累計總和做到這一點:

select Id, TimeUse, IdCustomer, Created, 
     (case when sum(timeuse) over (partition by idcustomer order by id) < 10 then 0 
      else timeuse 
     end) as timecalc 
from table t; 

你可以做同樣的事情在使用outer apply或子查詢更早版本。

如果你想要一個更新,只需要使用一個CTE:

with toupdate as (
     select t.*, 
      (case when sum(timeuse) over (partition by idcustomer order by id) < 10 then 0 
        else timeuse 
       end) as new_timecalc 
     from table t 
    ) 
update toupdate 
    set timecalc = new_timecalc; 

編輯:

下面將任何版本的SQL Server的工作:

with toupdate as (
     select t.*, 
      (case when (select sum(t2.timeuse) 
         from table t2 
         where t2.idcustomer = t.idcustomer and 
           t2.id <= t.id 
         ) < 10 then 0 
        else timeuse 
       end) as new_timecalc 
     from table t 
    ) 
update toupdate 
    set timecalc = new_timecalc; 
+0

謝謝你好..請問這些適用於SQL Server 2012? – Beaker 2014-11-25 14:02:46

+0

@Beaker。 。 。他們全部。 – 2014-11-25 14:07:13

+0

這只是我在'訂單'附近得到一個無效的語法。我看不出爲什麼... – Beaker 2014-11-25 14:15:49