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 Datemade
per PostId
with row_number
. Then you can search for the most recent 5 posts:
select top 5 PostId
from (
select PostId
, Datemade
, row_number() over (partition by PostId
order by Datemade) as rn
from dbForumEntry
) SubQueryAlias
where rn = 1 -- Most recent row per PostId
order by
Datemade desc
Alternatively, you can achieve the same with a group by
subquery:
select top 5 PostId
from (
select PostId
, max(Datemade) as LastDate
from dbForumEntry
group by
PostId
) SubQueryAlias
order by
LastDate desc
If dbForumEntry
has an ID column (say ForumEntryId
), a query like this might perform better. The database can run this without compiling the row_number
or max(Datemade)
for the entire table.
select top 5 PostId
from dbForumPosts fp
where not exists -- No later entry for the same post exists
(
select *
from dbForumPosts fp2
where fp2.PostId = fp.PostId
and fp2.ForumEntryId > fp.ForumEntryId
)
order by
Datemade desc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With