我正在尝试将列值与同一个表中之前的后续行列值进行比较。我在网上看到了一些解决方案但无法满足我的需求。
ALTER PROCEDURE [dbo].[compare_results_by_id]
@history_id int
AS
BEGIN
--declare table to insert old value and new value
declare @HistoryLog table (ColumnName varchar(100), OldValue varchar(max), NewValue varchar(max), updated_by int)
declare @previousID int
SELECT [history_id]
,[first_name]
,[last_name]
,[occupation]
,[updated_by]
FROM History_Table where history_id = @history_id
-- get previous row
SELECT @previousID = P.PreviousID
FROM
(SELECT MAX(D.history_id) PreviousID
FROM History_Table D
WHERE informant_history_id < @history_id) P
-- TODO Compare results
END
如何循环并比较两行的列值?有没有更好的方法?请告诉我。
答案 0 :(得分:0)
SELECT c.history_id, max(p.history_id)
FROM History_Table c
LEFT JOIN History_Table p
on p.history_id < c.history_id
GROUP BY c.history_id;
你可能想要使用带有rn的cte
with cte as
( SELECT [history_id]
, [first_name]
, [last_name]
, [occupation]
, [updated_by]
, row_number() over (order by [history_id] ) as rn )
select c.*, n.*
from cte as c
left join cte as p
on c.rn = n.rn-1;