TSQL - 下一个不同行的LEAD

时间:2015-02-25 10:56:58

标签: tsql analytic-functions

有没有办法使用引导功能,这样我可以获得更改某些内容的下一行,而不是它在哪里?

在这个例子中,RowType可以在' in'或者' out',对于每个' in'我需要知道下一个RowNumber已成为' out'。我一直在玩引导功能,因为它非常快,但是我还没有能够让它工作。我只需要真正做到以下几点,即RowType的分区,它不是当前行中的那个。

select
RowNumber
,RowType --In this case I am only interested in RowType = 'In'
, Lead(RowNumber) 
    OVER (partition by "RowType = out" --This is the bit I am stuck on--
          order by  RowNumber ASC) as NextOutFlow
from table
order by RowNumber asc 

提前感谢您提供任何帮助

2 个答案:

答案 0 :(得分:1)

我不会使用lead()而是使用outer apply为类型为out的所有行返回类型为in的下一行:

select RowNumber, RowType, nextOut 
from your_table t
outer apply (
  select min(RowNumber) as nextOut 
  from your_table 
  where RowNumber > t.RowNumber and RowType='Out'
) oa
where RowType = 'In'
order by RowNumber asc 

给出样本数据,如:

RowNumber   RowType
1           in
2           out
3           in
4           in
5           out
6           in

这将返回:

RowNumber   RowType nextOut
1           in      2
3           in      5
4           in      5
6           in      NULL

答案 1 :(得分:0)

我认为这会有效 如果您将使用位字段输入,那么您将获得更好的性能

;with cte1 as 
(
  SELECT [inden], [OnOff]
       , lag([OnOff]) over (order by [inden]) as [lagOnOff]
    FROM [OnOff] 
),   cte2 as
(
  select [inden], [OnOff], [lagOnOff]
       , lead([inden]) over (order by [inden]) as [Leadinden]
    from cte1 
   where [OnOff] <> [lagOnOff]
      or [lagOnOff] is null
 )
 select [inden], [OnOff], [lagOnOff], [Leadinden]
   from cte2 
  where [OnOff] = 'true'

可能比较慢,但如果你有正确的索引可能会起作用

select t1.rowNum as 'rowNumIn', min(t2.rownum) as 'nextRowNumOut' 
  from tabel t1 
  join table t2 
    on t1.rowType = 'In' 
   and t2.rowType = 'Out'
   and t2.rowNum > t1.rowNum  
   and t2.rowNum < t1.rowNum + 1000  -- if you can constrain it 
 group by t1.rowNum