0

我正在尝试从 Threads 表中返回带有线程的最新 5 个主题。然后我还需要加入主题表以将 topic_name + 从线程表连接返回到作者表并返回作者姓名。

如果一个主题在最近的 x 个帖子中出现多次,我只想要最近(最高)的线程 ID 信息。

SELECT distinct top 5 Topic_ID, Thread_ID from tblThread ORDER BY Thread_ID DESC

只返回 5 个最近的线程 ID,如下所示

topic_id - Thread_id

852 - 2905

852 - 2904,

850 - 2903,

937 - 2902,

937 - 2901

我要返回 852 - 2905 + 其他字段,主题名,作者名

850 - 2903 + ..

937 - 2902 + ...

&接下来的两个主题ID

提前致谢 :)

4

3 回答 3

0

像这样的东西应该可以解决问题(尽管您需要在那里使用真实的表和列):

;WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY Topic_ID ORDER BY Thread_ID DESC) RN
    FROM tblThread 
)
SELECT  A.Topic_ID,
        A.Thread_ID,
        B.Topic_Name,
        C.Author_Name
FROM CTE A
INNER JOIN tblTopic B
    ON A.Topic_ID = B.Topic_ID
INNER JOIN tblAuthor C
    ON A.Author_ID = C.Author_ID
WHERE RN = 1
于 2013-02-15T16:08:34.633 回答
0

这行不通:

select topic, max(thread) as thread from tblThread
group by topic
order by thread desc

You would do whatever joins you need after that.

于 2013-02-15T16:31:27.987 回答
0

final answer:

;WITH CTE AS
(
    SELECT top 10 *, ROW_NUMBER() OVER(PARTITION BY Topic_ID ORDER BY Thread_ID DESC) RN
    FROM tblThread 
    ORDER BY tblThread.Thread_ID DESC
)
SELECT  tblThread.Topic_ID,
        tblThread.Thread_ID,
        tblTopic.Subject,
        tblAuthor.UserName
FROM CTE tblThread
INNER JOIN tblTopic
    ON tblThread.Topic_ID = tblTopic.Topic_ID
INNER JOIN tblAuthor
    ON tblThread.Author_ID = tblAuthor.Author_ID
WHERE RN = 1
于 2013-02-15T17:13:22.677 回答