Let's say I have a table like this (SQL Server 2008):
CREATE TABLE tbl (ID INT, dtIn DATETIME2, dtOut DATETIME2, Type INT)
INSERT tbl VALUES
(1, '05:00', '6:00', 1),
(2, '05:00', '7:00', 1),
(3, '05:01', '8:00', 1),
(4, '05:00', '8:00', 1),
(5, '05:00', '6:00', 2),
(6, '05:00', '7:00', 2),
(7, '05:00', '7:00', 3),
(8, '04:00', '7:00', 3)
I need to delete all records of the same "type" (if 2 or more are found) with the same "dtIn" for my "type", except for one with the largest "dtOut". In other words, the above table should lead to the following:
(3, '05:01', '8:00', 1), -- no matching 'dtIn' for 'type' = 1
(4, '05:00', '8:00', 1), -- largest 'dtOut' for 'type' = 1
(6, '05:00', '7:00', 2), -- largest 'dtOut' for 'type' = 2
(7, '05:00', '7:00', 3), -- no matching 'dtIn' for 'type' = 3
(8, '04:00', '7:00', 3) -- no matching 'dtIn' for 'type' = 4
How do you even select multiple rows with the same type from the same table. You cannot do select * from tbl where type = type .... In any case, I would appreciate help in this ...