引导和分区功能

时间:2019-03-25 21:38:47

标签: sql sql-server tsql

这是我的输入表

create table #table1 (id int, FN varchar(20), startdate varchar(20), id1  varchar)

insert #table1
  select 1, 'Joe', '2019-01-01', 'A'
  union select 1, 'Joe', '2019-01-01', 'B'
  union select 1, 'Joe', '2019-01-05', 'C'
  union select 1, 'Joe', '2019-01-05', 'D'
  union select 1, 'Joe', '2019-01-06', 'E'
  union select 2, 'john', '2019-01-05', 'F'
  union select 2, 'john', '2019-01-06', 'G'
  union select 2, 'john', '2019-01-06', 'H'
  union select 2, 'john', '2019-01-07', 'I'

我尝试了以下代码

 select *
   , dense_rank() OVER (partition by id, fn  order by startdate) 
   , lead(startdate,1) OVER (partition by id, fn order by startdate) 
 from #table1
 order by id

output

但是我需要以下输出:

Expected output

1 个答案:

答案 0 :(得分:0)

我知道可能有更好的方法,但至少这是一个可行的解决方案:

select *, 
      (select MIN(startdate) 
       from #table1 t1 
       where t1.id = #table1.id and 
             t1.fn = #table1.fn and 
             t1.startdate > #table1.startdate) enddate
from #table1

结果

enter image description here