A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
you can use cross join and over functions combination very simple.
note:i use GuoxiongYuan-7218 data
DECLARE @T TABLE (
Id int,
Name varchar(50),
Accountno int,
Country varchar(50),
Active bit,
Insertdate date
);
INSERT INTO @T VALUES
(1, 'Chris', 13456, 'Us', 1, '1995-04-23'),
(1, 'Chris', 6784, 'Us', 0, '1996-05-24'), (1, 'Chris', 6785, 'Us', 0, '1996-05-24');
select * from @T x
select Id,Name,Accountno,c PreviousAccountNo,Country,Insertdate from(
select *,ROW_NUMBER() over (partition by Id,Name order by c ) rn from(
select t.*,y.Accountno as c from @T t cross join @T y
where t.Active=1 and y.Active=0
)x
)y where rn=1
(3 rows affected)
Id Name Accountno Country Active Insertdate
----------- -------------------------------------------------- ----------- -------------------------------------------------- ------ ----------
1 Chris 13456 Us 1 1995-04-23
1 Chris 6784 Us 0 1996-05-24
1 Chris 6785 Us 0 1996-05-24
(3 rows affected)
Id Name Accountno PreviousAccountNo Country Insertdate
----------- -------------------------------------------------- ----------- ----------------- -------------------------------------------------- ----------
1 Chris 13456 6784 Us 1995-04-23
(1 row affected)