You'll need to use a correlated subquery.
The JOIN query you posted is a good starting point:
Code:
SELECT TheCase.Status, Incident.SolutionCode, TheCase.TheCaseID, Incident.RecordDate
FROM TheCase INNER JOIN Incident ON
TheCase.TheCaseID = Incident.TheCaseID
The resultset from this will list all the rows for all TheCases with all their incidents.
We just need to add WHERE clauses to select only the rows we want from that resultset. There are two conditions for these rows. The first is we are only interested in rows where RecordDate is a maximum for a given TheCaseID. The second is that of those, we are only interested in rows where TheCase.Status is not equal to Incident.SolutionCode.
Of course, the second WHERE clause is trivial, and we'll just AND the two clauses together to only select rows which satisfy both conditions.
To find the row with the maximum RecordDate for a given TheCaseID, we would construct a query like the following. For now, let's assume the TheCaseID we are interested in is a parameter. The query would be
Code:
SELECT MAX(RecordDate) FROM Incident WHERE TheCaseID=@parameter
Simple enough.
What we want, though, is to execute this query for each value of TheCaseID, in effect substituting each value for the parameter. This is where a correlated subquery comes in. This kind of query is in effect executed for every row of the outer, containing query. We do this by setting up a WHERE clause in the subquery which relates to the TheCaseID in the outer query. Since both queries refer to the same table, we'll need to assign an alias (or
correlation name) to the table so each query will know which value it is referring to:
Code:
SELECT TheCase.Status, I1.SolutionCode, TheCase.TheCaseID, I1.RecordDate
FROM TheCase INNER JOIN Incident I1 ON
TheCase.TheCaseID = I1.TheCaseID
WHERE I1.RecordDate=
(SELECT MAX(RecordDate) FROM Incident I2 WHERE I1.TheCaseID=I2.TheCaseID)
AND TheCase.Status<>I1.SolutionCode;
should do the trick.
It's tough to refrain from pointing out that had your tables been properly normalized so that the Status value was not duplicating the SolutionCode, you wouldn't have had this problem in the first place. ;)
Jeff Mason
Custom Apps, Inc.
www.custom-apps.com