需要在下面的表1中计算field3
,根据以下规则比较当前记录中的字段值和当前+ n毫秒(t0 +nms
)的记录
WHEN type = 0 , look at record at t0 + 8ms, IF field2@t8 = field2@t0 && field1@t8 = field1@t0 + 1 THEN 1 ELSE 0
WHEN type = 1,look at record at t0 + 16ms , IF field2@t16 = field2@t0 && field1@t16 = field2@t0 + 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 field1@t0 +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 field1@t0 + 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 :(得分: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
答案 1 :(得分:0)
如果不要求性能,那么可以通过临时表和游标
来完成声明@table 将数据插入@table
声明游标
循环游标{计算field3并插入@table}