我正在尝试从结果集中获取先前的值。
我有一个表'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
答案 0 :(得分: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
答案 1 :(得分: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