The statuses are what is referred to as a slowly changing dimension. One way to deal with these is to have an "effective" and "end" date for the records. With EffDate
and EndDate
, the query that you want would be quite easy, either:
select *
from IssueStatus ist
where EndDate is NULL
or
where EndDate = '9999-01-01' -- or whatever your far out future date is
The downside is that inserting a new status requires two steps:
- Set the
EndDate
of the current status - Insert a new record
You would typically encapsulate this logic in a stored procedure or trigger.
Given your data structure, you can get the most recent status by using not exists
:
select ist.*
from IssueStatus ist
where not exists (select 1
from IssueStatus ist2
where ist2.issueId = ist.issueId and
ist2.IssueStatusDate > ist.IssueStatusDate
)
The logic is "Get me all rows from IssueStatus
where the given Issue has no later status date." That is equivalent to saying: "Get me the row with the maximum date." But for some reason, the database engine will do a good job optimizing this query when you have an index on IssueStatus(IssueId, IssueStatusDate)
.