如何获得下一个/上一个记录号? (第2部分)

时间:2013-09-09 07:36:36

标签: sql sql-server sql-server-2008

我正在使用solution from @peterm 它有效。

但是我还有另外一个问题,我怎样才能得到如下结果:

  Name   | SO No.   | Previous SO | Previous SO Details
  ---------------------------------------------------
  Adrian | SO-00005 | SO-00002    | details SO-00002

数据样本:

Name   | SO No.   | SO Details
------------------------------------
Adrian | SO-00001 | details SO-00001
Adrian | SO-00002 | details SO-00002
Bianca | SO-00003 | details SO-00003
Carrie | SO-00004 | details SO-00004
Adrian | SO-00005 | details SO-00005
Bianca | SO-00006 | details SO-00006
Adrian | SO-00007 | details SO-00007

SqlFiddle

2 个答案:

答案 0 :(得分:1)

以下是实现此目的的一种方法:

with CTE_table_1 as(
  select name
       , so_no
       , details
       , row_number() over(partition by name 
                           order by so_no) as rn
    from table1
  )
select name
     , so_no
     , (select max(so_no)
          from cte_table_1 q
         where q.rn = s.rn - 1 -- here you can regulate how far back you want to go 
           and s.name = q.name) as prev_so_no
     , details
     , (select max(details)
          from cte_table_1 q
         where q.rn = s.rn - 1
           and s.name = q.name) as prev_details
  from cte_table_1 s

SQLFiddle Demo #1

SQLFiddle Demo #2

答案 1 :(得分:0)

在Sql Server 2012中新增的功能是添加哪些称为窗口函数滞后和引导。 它们可以显示聚合函数的上一个或下一个结果。 ;)