1

我正在尝试从结果集中获取先前的值。
我有一个看起来像这样的表'TableA' -

ColumnID    ColumnValue
1           100
2           NULL
3           NULL
4           0
5           10
6           100
7           100

我使用此查询得到以下结果集 -

"Select ColumnID, ColumnValue from TableA
WHERE ColumnValue = 100
ORDER BY ColumnID DESC"

ColumnID    ColumnValue

7           100         
6           100         
1           100 

现在我需要在我拥有的结果集中再添加一列(上一个查询),它给出了现有结果集中“WITHIN”中的上一个 ColumnID。
我在结果集中提到过,因为 ColumnID 不遵循任何顺序。就像在这种情况下,它从 7、6 然后直接变为 1。

ColumnID    ColumnValue PreviousColumnID
7           100         6
6           100         1
1           100         NULL

有什么帮助吗?我使用 SQL Server 2008

4

2 回答 2

1

这有点令人费解,但似乎有效:

select ColumnID, ColumnValue,
    (select top 1 ColumnID
     from (Select ColumnID, ColumnValue from TableA
           WHERE ColumnValue = 100) T2
     where T2.ColumnId < TableA.ColumnId
     order by ColumnID DESC)
from TableA
WHERE ColumnValue = 100
ORDER BY ColumnID DESC

这是一个完整的测试脚本:

create table TableA (ColumnID int, ColumnValue int)

insert TableA values (1, 100)
insert TableA values (2, NULL)
insert TableA values (3, NULL)
insert TableA values (4, 0)
insert TableA values (5, 10)
insert TableA values (6, 100)
insert TableA values (7, 100)

Select ColumnID, ColumnValue from TableA
WHERE ColumnValue = 100
ORDER BY ColumnID DESC

select ColumnID, ColumnValue,
    (select top 1 ColumnID
     from (Select ColumnID, ColumnValue from TableA
           WHERE ColumnValue = 100) T2
     where T2.ColumnId < TableA.ColumnId
     order by ColumnID DESC)
from TableA
WHERE ColumnValue = 100
ORDER BY ColumnID DESC
于 2013-10-23T14:47:45.860 回答
0

使用假的排序列num

SELECT MIN (CASE x WHEN 0 THEN ColumnID END) AS ColumnID
    , MIN (CASE x WHEN 0 THEN ColumnValue END) AS ColumnValue
    , MIN (CASE x WHEN 1 THEN ColumnID END) AS ColumnID_prev
FROM (
    SELECT ColumnID, ColumnValue, ROW_NUMBER() OVER(ORDER BY ColumnID DESC) AS num
    FROM TableA
    WHERE ColumnValue = 100
) T
CROSS JOIN (VALUES(0),(1))x(x)
WHERE num - x > 0
GROUP BY num - x
于 2013-10-23T14:51:02.233 回答