8

起動したい次のクエリがあります。

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-投稿の多くのエントリがあります。

私が欲しいのは、最新のアクティビティを含む投稿(最新の更新されたエントリを含む投稿)を取得することです。

4

1 に答える 1

6

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
于 2012-11-04T14:59:09.590 に答える