我有一个表,该表跟踪对实体的更改,并且我试图提取更改。结构大致如下:
| RowNumber | Value | SourceID| TargetID |
| 1 | A | 100 | 50 |
| 2 | B | 100 | 100 |
| 3 | C | 200 | 100 |
我的选择是
select t1.Value as Old, t2.Value as New from MyTable t1
inner join MyTable t2 on t1.SourceID = t2.TargetID
where t1.value != t2.value
哪个给我:
|Old|New|
|A | B |
|A | C |
|B | C |
问题是,数据从A-> B,然后从B-> C更改。它实际上从未从A-> C更改,并且我一生都找不到在一个查询中执行此操作的方法,我意识到游标可以按顺序遍历行来实现此目的。
在一个查询中有可能吗?
答案 0 :(得分:3)
您可以使用ROW_NUMBER窗口功能查找下一个。
示例:
declare @MyTable table (RowNumber int primary key identity(1,1), [Value] varchar(30), SourceID int, TargetID int);
insert into @MyTable ([Value], SourceID, TargetID) values
('A', 100, 50),
('B', 100, 100),
('C', 200, 100);
SELECT Old, New
FROM
(
select
t1.[Value] as Old,
t2.[Value] as New,
row_number() over (partition by t1.RowNumber order by t2.RowNumber) as RN
from @MyTable t1
join @MyTable t2
on t2.TargetID = t1.SourceID AND t2.RowNumber > t1.RowNumber
) q
WHERE RN = 1;
返回:
Old New
A B
B C