1

我在 SQL Server 中有一个表,对于rtime的每一行t,我想为wheret + i的某些函数找到第一个表。rabs(f(r, t + i) - f(r, t)) > epsilon

我可以想象用两个游标来做这件事,但这似乎效率很低。

那里有任何 T-SQL 大师有什么建议吗?

4

2 回答 2

1

我不是相关子查询的忠实粉丝。但是,在这种情况下它似乎很有用。以下代码根据您的条件返回给定行之后第一行的最小“序列号”:

with t as (
    select t.*, f(r, t) as fval, row_number() over (order by <ordering>) as seqnum
    from table t
)
select t.*,
       (select min(t2.seqnum)
        from t t2
        where t2.seqnum > t.seqnum and
              abs(t2.fval - t.fval) > <epsilon>
       ) as next_seqnum
from t

要完成这项工作,您需要指定<ordering><epsilon>。是你如何知道行的顺序(t如果我不得不猜测的话,这将是一个很好的猜测)。

于 2012-09-27T21:50:47.477 回答
1
select a.t, b.t  --- and what other columns you need
from tbl a -- implicitly each row of table
cross apply (
    select top(1) * -- the first, going upwards along b.t
    from tbl b
    where a.t < b.t -- look for records with later t than the source row
      and <here's your function between a row and b row>
    order by b.t asc
) x
于 2012-09-27T21:53:39.917 回答