2

我正在使用来自@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

4

2 回答 2

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 演示 #1

SQLFiddle 演示 #2

于 2013-09-09T07:52:04.013 回答
0

在 Sql Server 2012 中添加了称为窗口函数 lag 和 Lead 的新功能。它们可以显示聚合函数的上一个或下一个结果。;)

于 2013-09-09T08:43:18.267 回答