在SQL Server中如何移动两列的行

时间:2016-08-18 18:18:55

标签: sql-server

这是原始表

Name    Marks_Original
Anil    10
Ravi    20
Pooja   30
Sheela  40
Rohit   50
Vijay   60

我希望输出使用2个计算列,如下所示,我的第1列记录是静态的,但我的第2列记录分别向上和向下移动到第1列

Name    Marks_1  Marks_2
Anil    0        20
Ravi    10       30
Pooja   20       40
Sheela  30       50
Rohit   40       60
Vijay   50       0

1 个答案:

答案 0 :(得分:1)

尝试窗口函数(假设序列为Marks_Original)

Select *
      ,Marks_1 = Lag(Marks_Original,1,0) over (Order By Marks_Original)
      ,Marks_2 = lead(Marks_Original,1,0) over (Order By Marks_Original)
 From  YourTable
 Order By Marks_Original

返回

Name    Marks_Original  Marks_1 Marks_2
Anil    10              0       20
Ravi    20              10      30
Pooja   30              20      40
Sheela  40              30      50
Rohit   50              40      60
Vijay   60              50      0