Here is the situation:
I have a database of 'tickets', and we track changes to the tickets each time they are saved. I am specifically looking at status changes, which track with the following format:
STATUS:{FROM}:{TO}
with {FROM} and {TO} changing to the respective statuses. What I need to do is generate numbers by weeks of the amount of tickets that were 'open' (meaning in draft status) at the end of any given week, say for the past 12 weeks. However, you are not limited to 'closing' a ticket and then reopening it, or making multiple changes in a single week.
So, what I need to do is modify the SQL below to ONLY consider the most recent "action" for any given entry. This way we avoid the problem of having entries that were 'closed' appear in the open count because they had been opened earlier.
SELECT track.historyID
FROM RS_HistoryTracker track
WHERE (track.action = 'STATUS:INITIAL:DRAFT'
OR track.action = 'STATUS:DELETED:DRAFT'
OR track.action = 'STATUS:DRAFT:DRAFT')
AND track.trackDateTime <= @endOfWeek
However, this statement is contained within another select statement, and is used to generate a complete list of history items:
SELECT COUNT(DISTINCT his.historyID) AS theCount
FROM RS_History his
WHERE his.historyID IN
(SELECT track.historyID
FROM RS_HistoryTracker track
WHERE (track.action = 'STATUS:INITIAL:DRAFT'
OR track.action = 'STATUS:DELETED:DRAFT'
OR track.action = 'STATUS:DRAFT:DRAFT')
AND track.trackDateTime <= @endOfWeek)
So how do I make the inner select consider only the most recent tracked 'action' that occured up to or on the endOfWeek date? HistoryTracker contains a datetime stamp column.