T-SQL查找特定值在范围内的时间长度

时间:2012-09-27 21:36:30

标签: sql sql-server tsql

我在SQL Server中有一个表,对于r的每一行t,我希望找到t + i的某个函数的第一个r abs(f(r, t + i) - f(r, t)) > epsilon

我可以想象用两个游标来做这个,但这看起来非常低效。

那里的任何T-SQL专家有什么建议吗?

2 个答案:

答案 0 :(得分: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是一个很好的猜测,如果我不得不猜测。)

答案 1 :(得分: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