检索记录的前一列值

Retrieving a record's previous column value

假设我有这张表:

|ID|ForeignKey|Number|
| 1|    A     |     5|
| 2|    B     |     3|
| 3|    A     |     2|
| 4|    B     |     5|

我想得到这个输出:

|ForeignKey|PrevNumber|CurNumber|
| A        |         0|        5|
| B        |         0|        3|
| A        |         5|        2|
| B        |         3|        5|

那么如何检索记录的先前属性? 我尝试使用不同类型的连接,如左、内,但无济于事

试试这个:

SELECT A.ForeignKey, COALESCE(B.Number, 0) AS PrevNumber, A.Number AS CurNumber 
FROM table1 A 
LEFT JOIN table1 B ON A.ForeignKey = B.ForeignKey AND A.ID > B.ID
ORDER BY A.ID

勾选SQL FIDDLE DEMO

输出

| FOREIGNKEY | PREVNUMBER | CURNUMBER |
|------------|------------|-----------|
|          A |          0 |         5 |
|          B |          0 |         3 |
|          A |          5 |         2 |
|          B |          3 |         5 |

::编辑::

SELECT A.ForeignKey, COALESCE(B.Number, 0) AS PrevNumber, A.Number AS CurNumber, COALESCE(C.Number, 0) AS NextNumber
FROM table1 A 
LEFT JOIN table1 B ON A.ForeignKey = B.ForeignKey AND A.ID > B.ID
LEFT JOIN table1 C ON A.ForeignKey = C.ForeignKey AND A.ID < C.ID
ORDER BY A.ID

勾选SQL FIDDLE DEMO

输出

| FOREIGNKEY | PREVNUMBER | CURNUMBER | NEXTNUMBER |
|------------|------------|-----------|------------|
|          A |          0 |         5 |          2 |
|          B |          0 |         3 |          5 |
|          A |          5 |         2 |          0 |
|          B |          3 |         5 |          0 |

试试这个

select d.FK,ISNULL(d.Prev,0) as Prev,d.Num1 as CurNumber from (
select t.Number as Num1,t.ForeignKey as FK,
(select top 1 NUmber from test where ID=t.ID-2) as Prev
   from test t
   )d

输出

FK  Prev    CurNumber
A   0       5
B   0       3
A   5       2
B   3       5