It seems like this title has been used many times before, unfortunately I don’t know how else to describe my problem. So, first off, if you have a suggestion for a better title that will help future searchers, fire away!
Anyway, my problem is trying to write the SQL to return a resultset based on a set of rules applied to the following schema:
TABLE: Tests
COLUMNS: ID (PK), Name
TABLE: TestVersions
COLUMNS: TestID (PK), Version (PK), IsActive
TABLE: TestSessions
COLUMNS: TestID (PK), TestVersion (PK), UserID (PK), Iteration (PK), Completed, CompletionDate
There is a relationship between [Tests] and [TestVersions] on [Tests].[ID] = [TestVersions].[TestID]. There is also a relationship between [TestSessions] and [TestVersions] on [TestSessions].[TestID] = [TestVersions].[TestID] AND [TestSessions].[TestVersion] = [TestVersions].[Version]
The result set should return [Tests].[ID], [Tests].[Name] and [TestVersions].[Version] based on the following rules:
- Any Test that has an associated record in TestSessions where Complete is false.
- The maximum Version for any Test that has no associated records in TestSessions but IsActive is true.
- This one is the complicated one. If a Test has associated records in TestSessions where all are completed (Complete is true) and has at least one associated record in TestVersions with IsActive true, I need to verify that the most recent CompletionDate is at least 30 days ago and, if so, return the highest Version from TestVersions.
Hopefully this makes sense.
Here’s a quick script that creates temp tables, fills them with data, and shows you how i’d approach the problem you’re having. Let me say up front that this kind of stuff is sometimes best left to the business logic layers. Also, I’m not sure that your description is very accurate because there seem to be some inconsistencies. With that said, I hope you can take away how to approach your problem, break it down into parts and solve it. Don’t worry about optimizing up front, just write clean and logical code. Optimizer will tell you if you’re making any mistakes. This assumes SQL Server 2008: