2012-11-04 57 views
7

我有以下查询我要火:SQL查询 - 结合DISTINCT和TOP?

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)。这里有0个很多条目。

我想是与最近的活动(在最新更新的条目职位)的get职位。

+0

您正在使用哪个数据库管理系统? –

+0

的SQL Server 2008 R2(MSSQL) –

+0

还能有'Datemade'每'PostId'不止一个?如果是的话,哪一个用于订购目的? –

回答

5

你可以找到每PostId最近Datemaderow_number。然后,你可以搜索最近的5个帖子:

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 

或者,你可以实现一个group by子查询相同:

select top 5 PostId 
from (
     select PostId 
     ,  max(Datemade) as LastDate 
     from dbForumEntry 
     group by 
       PostId 
     ) SubQueryAlias 
order by 
     LastDate desc 

如果dbForumEntry有一个ID列(比如ForumEntryId),查询这样可能会表现更好。数据库可以在不编译整个表的row_numbermax(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 
+0

非常感谢文本 - 它真的:-)帮助!谢谢。 –