I am trying to alter the rows with the following conditions in SQL Server.
- Merge all rows with similar
code
taking first date from the 1st row and last date from the last row. - Un-similar rows will remain as it is.
CREATE TABLE ABCD(
id int,
FirstDate date,
LastDate date,
code varchar(23)
);
Insert into ABCD VALUES
(1, '2022-12-12','2022-12-12', 'A'),
(2, '2022-12-13','2022-12-13', 'A'),
(3, '2022-12-15','2022-12-15', 'A'),
(4, '2022-12-16','2022-2-16', 'B'),
(5, '2022-12-18','2022-12-18', 'A'),
(5, '2022-12-19','2022-12-19', 'A'),
(6, '2022-12-20','2022-12-20', 'C')
SELECT * from ABCD
Expected result is
(1, '2022-12-12','2022-12-15', 'A'),
(2, '2022-12-16','2022-2-16', 'B'),
(3, '2022-12-18','2022-12-19', 'A'),
(4, '2022-12-20','2022-12-20', 'C')
Tried
SELECT *
FROM ABCD #A
INNER JOIN ABCD #B on #A.code != #B.code AND #A.id = #B.id
I'm unable to think of any logic to get this working. Suggestions are highly appreciated. Thanks!