I have the following query I want to fire:
SELECT DISTINCT TOP(5) fp.PostId FROM dbForumPosts fp
LEFT JOIN dbForumEntry fe ON fp.PostId = fe.PostId
Order by fe.Datemade DESC
However, when I fire it, I get the error:
Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
I tried to change the query, so it used GROUP BY instead, but then I have the following problem:
Msg 8127, Level 16, State 1, Line 4
Column "dbForumEntry.Datemade" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
WHAT DO I WANT:
Think of this as a forum. There are posts (dbForumPosts) and entries (dbForumEntry). There are 0-many entries pr post.
What I want is to the get posts with the most recent activity (posts with the latest updated entries in).
You could find the most recent
DatemadeperPostIdwithrow_number. Then you can search for the most recent 5 posts:Alternatively, you can achieve the same with a
group bysubquery:If
dbForumEntryhas an ID column (sayForumEntryId), a query like this might perform better. The database can run this without compiling therow_numberormax(Datemade)for the entire table.