SQL查询 - 结合DISTINCT和TOP?

时间:2012-11-04 14:51:52

标签: sql sql-server join distinct

我想要触发以下查询:

SELECT DISTINCT TOP(5) fp.PostId FROM dbForumPosts fp
LEFT JOIN dbForumEntry fe ON fp.PostId = fe.PostId
Order by fe.Datemade DESC

然而,当我开火时,我收到错误:

Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

我尝试更改查询,因此它使用了GROUP BY,但后来我遇到了以下问题:

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.

我想要什么:

将此视为一个论坛。有帖子(dbForumPosts)和条目(dbForumEntry)。 pr post有0多个条目。

我想要的是获取最近活动的帖子(包含最新更新条目的帖子)。

1 个答案:

答案 0 :(得分:6)

您可以使用Datemade找到PostIdrow_numberselect 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 。然后,您可以搜索最近的5个帖子:

group by

或者,您可以使用select top 5 PostId from ( select PostId , max(Datemade) as LastDate from dbForumEntry group by PostId ) SubQueryAlias order by LastDate desc 子查询实现相同的目标:

dbForumEntry

如果ForumEntryId有ID列(比如说row_number),那么这样的查询可能会有更好的效果。数据库可以在不编译整个表的max(Datemade)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 的情况下运行它。

{{1}}