2016-01-19 16 views
0

需要計算field3 table1中低於當前記錄和記錄在下面的規則基於當前+ N毫秒(t0 +nms)比較字段值計算新領域SQL - 基於當前記錄的字段和字段ñ毫秒後

WHEN type = 0 , look at record at t0 + 8ms, IF [email protected] = [email protected] && [email protected] = [email protected] + 1 THEN 1 ELSE 0

WHEN type = 1,look at record at t0 + 16ms , IF [email protected] = [email protected] && [email protected] = [email protected] + 5 THEN 1 ELSE 0

IF there is no record at t0+8ms for type=0 or no record at t0+16ms in case of type=1 THEN 0

表1

Time    type  field1 field2 field3 
    09:37.43.745  0  0   0  0 # for record at t0 + 8ms - xx.753 , field2 is SAME, but field1 is not [email protected] +1 
    09:37.43.746  0  0   1  1 # for record at t0 + 8ms - xx.754, field2 is SAME, field1 is incremented by 1 
    09:37.43.747  0  0   2  0 # no record at t0 + 8ms 
    09:37.43.748  0  0   3  1 # for record at t0 + 8ms - xx.756, field2 is SAME, field1 is incremented by 1 
    09:37.43.749  0  0   4  0 # no record at t0 + 8ms 

    09:37.43.753  0  0   0  0 # no record at t0 + 8ms 
    09:37.43.754  0  1   1  0 # for record at t0 + 8ms - xx.772, field2 is SAME, but field1 is not [email protected] + 1 
-- 09:37.43.755/757 - no records 
    09:37.43.756  0  1   3  0 # no record at t0 + 8ms 

    09:37.43.762  0  0   1  0 # no record at t0 + 8ms 

    09:37.43.772  1  0   0  1 # for record at t0 + 16ms - xx.788, field2 is SAME AND field1 is incremented by 5  
    09:37.43.776  1  0   1  0 # for record at t0 + 16ms - xx.792, field2 is SAME BUT field1 is NOT incremented by 5 
    09:37.43.780  1  0   2  0 # no record at t0 + 16ms 
    09:37.43.788  1  5   0  0 # no record at t0 + 16ms 
    09:37.46.792  1  0   1  0 # no record at t0 + 16ms 
-- 09:37.46.796 - no records 

回答

0

如果性能不是要求那麼這可以通過一個臨時表和光標來進行

通過光標聲明@table 插入數據到@table

聲明遊標

環{計算field3並插入@table}

+0

性能是一個問題。 – user3206440

1

我認爲你正在尋找像下面這樣的東西。我開始將你的英文翻譯成SQL。

select t1.Time, 
     t1.Type, 
     t1.Field1, 
     t1,Field2 
     isnull(
     case when t2.field2 = t1.field2 and t2.field1 = t1.field1 + IIF(t1.Type=0, 1, 5) 
       then 1 else 0 end, 0) as Field3 
     from table1 as t1 
     left join table1 as t2 
     on case t1.type when 0 then DATEADD(millisecond, 8, t1.Time) 
         when 1 then DATEADD(millisecond, 16, t1.Time) end = t2.Time 
相關問題