Problem
Given the following two tables, I'd like to select all Ids for Posts that have their most recent (i.e. last) comment made in the given time span (e.g. Feb 2010).
The result of the query should only return Post ID 1, since the most recent comment for Post ID 2 is outside the range of the time span filter.
Question
I've created the SELECT
statement below that seems correct and handles all the test cases thrown at it.
However, in a quest to continue to improve my SQL skills, I'm asking the community if there is a "better" method to use for this scenario, any suggestions on improving the existing statement, and/or edge cases that are not covered.
Note that this is an loose translation of the actual tables, changed with the intent of making the question easier to understand. For what it's worth, I'm using SQL Server 2005.
Tables
Post
Id Text Visible
1 Post 1 1
2 Post 2 1
3 Post 3 0
. ...
n Post n 1
Comment
Id Post_Id Text CommentNumber Timestamp
1 1 Comment 1, Post 1 1 2/3/2010
2 1 Comment 2, Post 1 2 2/4/2010
3 2 Comment 1, Post 2 1 3/1/2010
. . .
n m Comment n, Post m x xx/xx/xxxx
SQL Command
SELECT [Id],[Text]
FROM [Post]
WHERE [Id] IN (
SELECT comment1.[Post_Id]
FROM (
SELECT max([CommentNumber]) as maxComment,
[Post_id]
FROM [Comment]
GROUP BY [Post_id]
) as comment2
INNER JOIN [Comment] as comment1 on comment1.[Post_id] = comment2.[Post_id]
WHERE comment1.[Timestamp] BETWEEN '2/1/2010 00:00:00.000' AND '2/28/2010 23:59:59.999'
AND comment1.[CommentNumber] = comment2.maxComment
)
AND [Post].[Visible] = 1
Bonus Question
Is it possible to create this query with NHiberate (either using the Criteria API or HQL)?