2017-08-21 80 views
-1

請讓我知道如何通過Excel中提供的公式計算E列。 enter image description here查找前9行的最小值和最大值

select ROW_NUMBER() OVER (ORDER BY [A] asc) AS id,A,B,C,0 as E into #temp from dbo.rawdata 
    order by id asc 
    ------------------------- 

    update #temp 
    set E=((select max(h.B) from(select top (9) b.B from #temp b where b.id<#temp.id order by b.id asc)h) + (select min(l.C) from(select top (9) c.C from #temp c where c.id<#temp.id order by id asc)l))/2 
    where id>10 

回答

1

有可能是一個更有效的方式來做到這一點,但這裏的使用OUTER APPLY一個方法:

;With Cte As 
(
    Select *, 
      Row_Number() Over (Order By A) As RN 
    From YourTable 
) 
Select T1.A, T1.B, T1.C, T1.D, X.E 
From Cte T1 
Outer Apply 
(
    Select (Max(T2.B) + Min(T2.C))/2 As E 
    From Cte T2 
    Where T2.RN >= (T1.RN - 9) 
    And  T2.RN < T1.RN 
    And  T1.RN >= 10 
) X 

UPDATE你的表使用這些值,可以使用以下:

;With Cte As 
(
    Select *, 
      Row_Number() Over (Order By A) As RN 
    From YourTable 
) 
Update T1 
Set  E = X.E 
From Cte T1 
Outer Apply 
(
    Select (Max(T2.B) + Min(T2.C))/2 As E 
    From Cte T2 
    Where T2.RN >= (T1.RN - 9) 
    And  T2.RN < T1.RN 
    And  T1.RN >= 10 
) X 
+0

但我需要更新我的t能通過e值 – MahdiIBM

+0

@MahdiIBM請在問題中指定。你能否詳細說明你想更新的內容? – Siyual

+0

store(Max(T2.B)+ Min(T2.C))/ 2 As E to my table – MahdiIBM