Hi PRA,
Please refer below SQL Query,
SQL
DECLARE @Person AS TABLE(Id INT,Name varchar(15))
INSERT INTO @Person VALUES(1, 'Rustam')
INSERT INTO @Person VALUES(2, 'Sadriddin')
INSERT INTO @Person VALUES(3, 'Muhammad')
INSERT INTO @Person VALUES(4, 'Sindbod')
DECLARE @Account AS TABLE(Id INT, PersonId Int, AccNumber Int, Amount numeric, openDate Date, closeDate Date)
INSERT INTO @Account VALUES(1, 1, 233232, '5000', '11-19-2019', '11-20-2020')
INSERT INTO @Account VALUES(4, 1, 233243, '8000', '10-12-2022', '')
INSERT INTO @Account VALUES(2, 2, 233233, '4000', '10-19-2019', '12-20-2020')
INSERT INTO @Account VALUES(5, 2, 233245, '9000', '11-11-2021', '')
INSERT INTO @Account VALUES(3, 3, 233234, '7000', '12-11-2019', '12-12-2021')
INSERT INTO @Account VALUES(6, 3, 233244, '7000', '12-12-2021', '12-13-2022')
INSERT INTO @Account VALUES(7, 4, 233234, '11000', '12-11-2022', '')
select ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY openDate DESC) as RowNo,
p.Id, p.Name, AccNumber, Amount, openDate, case closeDate when '1900-01-01' then NULL else closeDate end closeDate
INTO #Temp1
from @Account ac
inner join @Person p on ac.PersonId = p.Id
select ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY openDate ASC) as RowNo,
p.Id, p.Name, AccNumber, Amount, openDate, case closeDate when '1900-01-01' then NULL else closeDate end closeDate
INTO #Temp2
from @Account ac
inner join @Person p on ac.PersonId = p.Id
SELECT * INTO #Temp3 FROM #Temp1 WHERE RowNo = 1
SELECT * INTO #Temp4 FROM #Temp2 WHERE RowNo = 1
SELECT t3.Id,t3.Name,t3.AccNumber,t3.Amount,t3.openDate,t3.closeDate,
(SELECT t4.AccNumber FROM #Temp4 t4 WHERE t3.AccNumber <> t4.AccNumber AND t3.Id = t4.Id) 'prevAccNumber',
(SELECT t4.Amount FROM #Temp4 t4 WHERE t3.AccNumber <> t4.AccNumber AND t3.Id = t4.Id) 'prevAmount',
(SELECT t4.openDate FROM #Temp4 t4 WHERE t3.AccNumber <> t4.AccNumber AND t3.Id = t4.Id) 'prevOpenDate',
(SELECT t4.closeDate FROM #Temp4 t4 WHERE t3.AccNumber <> t4.AccNumber AND t3.Id = t4.Id) 'prevCloseDate'
FROM #Temp3 t3
Output
Id |
Name |
AccNumber |
Amount |
openDate |
closeDate |
prevAccNumber |
prevAmount |
prevOpenDate |
prevCloseDate |
1 |
Rustam |
233243 |
8000 |
12-10-2022 |
NULL |
233232 |
5000 |
19-11-2019 |
20-11-2020 |
2 |
Sadriddin |
233245 |
9000 |
11-11-2021 |
NULL |
233233 |
4000 |
19-10-2019 |
20-12-2020 |
3 |
Muhammad |
233244 |
7000 |
12-12-2021 |
13-12-2022 |
233234 |
7000 |
11-12-2019 |
12-12-2021 |
4 |
Sindbod |
233234 |
11000 |
11-12-2022 |
NULL |
NULL |
NULL |
NULL |
NULL |