I've built the following code to find records with more than 1 "tsqcallid". These are duplicates and I need to find the earliest record to delete it. The code below works great if the duplicate records have a different tsqClosedDate value. However, if they are the same, I need to be able to find the "NOT IN MAX(tsqClosedTime)". I'm having trouble figuring out how to use either CASE or IF,THEN to do this...any help appreciated.
Code:
SELECT CallID
FROM Detail d1
WHERE tsqCallID IN
(
SELECT tsqCallID
FROM Detail
WHERE tsqCallID IS NOT NULL
GROUP BY tsqCallID HAVING COUNT(*) > 1
)
AND tsqClosedDate NOT IN
(
SELECT MAX(tsqClosedDate)
FROM Detail d2
WHERE d2.tsqCallID = d1.tsqCallID
)