2010-05-26 75 views
0

以下是我正在通過遍歷記錄嘗試處理的內容。如何根據字段的總和更新記錄,然後使用總和來計算sql中的新值

我希望有一個更優雅的解決方案,如果可能的話,因爲我確信這不是在SQL中執行它的最好方法。

set @counter = 1 

declare @totalhrs dec(9,3), @lastemp char(7), @othrs dec(9,3) 

while @counter <= @maxrecs 
begin 
    if exists(select emp_num from #tt_trans where id = @counter) 
    begin 
    set @nhrs = 0 
    set @othrs = 0 

    select @empnum = emp_num, @nhrs = n_hrs, @othrs = ot_hrs 
    from #tt_trans 
    where id = @counter 

    if @empnum = @lastemp 
    begin 
     set @totalhrs = @totalhrs + @nhrs 

     if @totalhrs > 40 
     begin 
     set @othrs = @othrs + @totalhrs - 40 
     set @nhrs = @nhrs - (@totalhrs - 40) 
     set @totalhrs = 40 
     end 
    end 
    else 
    begin 
     set @totalhrs = @nhrs 
     set @lastemp = @empnum 
    end 

    update #tt_trans 
    set n_hrs = @nhrs, 
     ot_hrs = @othrs 
    where id = @counter and can_have_ot = 1 
    end 

    set @counter = @counter + 1 
end 

THX

+1

掛在秒。我認爲你現有的代碼有一些非常嚴重的邏輯問題。看起來您將每個員工的所有時間加起來,確定總時間和常規時間。然後更新每個員工的n_hrs(覆蓋它)和最後一條記錄的ot_hrs列。 我無法想象ypu'd想要這樣做的情況。所以有些事情是不對的。 你能用英文解釋你想做什麼嗎?也許給表格的內容之前/之後的例子? – JohnFx 2010-05-26 21:54:30

+0

基本上我需要做的是,在一段時間內有超過40個小時的所有員工都要調整自己的拳頭,以適應加班的事實。它退出n_hrs並將小時移動到ot_hrs,使總小時數保持不變。最終用戶應該能夠看到ot_hrs(何時破損40)發生的日子。 – Casey 2010-05-27 12:18:07

+0

實施例之前
EMP#n_hrs ot_hrs日期
1 8.2 0 1/1
1 8.5 0 1/2
1 8.6 0 1/3
1 8.7 0 1/4
1 8.0 0 1/5 2 10.3 0 1/1
2 10.6 0 1/2
2 12.0 0 1/3
2 10.0 0 1/4

EMP#n_hrs ot_hrs日期
1 8.2 0 1/1
1 8.5 0 1/2
1 8.6 0 1/3
1 8.7 0 1/4
1 6.0 2.0 1/5
2 10.3 0 1/1
2 10.6 0 1/2
2 12.0 0 1/3
2 7.1 2.9 1/4 – Casey 2010-05-27 12:23:20

回答

0
update #tt_trans 
    set n_hrs = case 
    when t2.totHrs > 40 
    then n_hrs - (t2.totHrs -40) 
    else n_hrs 
    end, 
    ot_hrs = case 
    when t2.totHrs > 40 
    then ot_hrs + (t2.totHrs -40) 
    else ot_hrs 
    end 
    from #tt_trans t1 
    join (select sum (n_hrs) as totHrs, emp_num from #tt_trans where can_have_ot =1 group by emp_num) t2 on t1.emp_num = t2.emp_num where t1.post_date = (select max(post_date)from #tt_trans where emp_num = t1.emp_num) 

基本上我修改了這段時間最後一個日期的小時數,並進行了適當的調整。感謝你們的迴應。這兩個回覆都讓我感動。

1

這是接近你想要什麼,但需要一旦你回答我關於你真正想實現的評論將被調整了一下。

update #tt_trans 
    set n_hrs = CASE WHEN T2.totHrs>40 
        THEN 40 
        ELSE T2.totHrs END, 
    ot_hrs= CASE WHEN T2.totHrs>40 
       THEN T2.totHrs-40 
       ELSE 0 END 
FROM #tt_trans trans T1 
INNER JOIN (SELECT SUM(@nhrs) totHrs, EmpNum 
      FROM #tt_trans 
      WHERE can_have_ot=1 
      GROUP BY EmpNum) T2 ON (T1.EmpNum=T2.EmpNum) 

WHERE can_have_ot = 1 
0

看起來您正在迭代,因爲您必須記錄跨多個記錄的給定員工的總小時數。您可以使用內部選擇來爲每個員工計算小時數,然後將該選擇加入到#tt_trans表中。從該連接寫入更新,並將您的邏輯放入更新列的CASE語句中。