I have the following file name changing log table.
ChangeNameLog(Date, OldName, NewName)
Primary key: Date, OldName
The data of the table looks like
Date OldName NewName 1/1 aaa bbb 1/2 bbb ccc 1/3 ccc bbb 1/4 bbb ddd 2/1 xx yy 2/2 yy zz
(The file name aaa was changed to bbb, and then to ccc, bbb, ddd later
The file name xx was changed to yy, and then to zz)
I want to get the oldest name for all the new names. The result will look like
Date NewName OldestName 1/2 bbb aaa 1/3 ccc aaa 1/4 ddd aaa 2/1 yy xx 2/2 zz xx
Is anyway to write a Transact-SQL (Version 2008 is fine) without using cursor to loop the logging table?
The following SQL can be used to prepare the data.
declare @log table (
Date Date, OldName varchar(20), NewName varchar(20) not null
primary key (Date, OldName)
);
-- The real table also have the following CK
-- create unique index IX_CK on @log (Date, NewName)
insert into @log values
('2012-01-01', 'aaa', 'bbb')
,('2012-01-02', 'bbb', 'ccc')
,('2012-01-03', 'ccc', 'bbb')
,('2012-01-04', 'bbb', 'ddd')
,('2012-01-05', 'ddd', 'eee')
,('2012-01-03', 'xx', 'yy')
,('2012-02-02', 'yy', 'zz')
,('2012-02-03', 'zz', 'xx')
;