选择不同的前5个Topic_ID,来自tblThread的Thread_ID ORDER BY Thread_ID DESC

时间:2013-02-15 15:58:31

标签: sql-server

我试图通过Threads表中的线程返回最新的5个主题。然后我还需要加入主题表,将topic_name +从线程表连接返回到author表并返回作者名称。

如果某个主题在最近的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

提前致谢:)

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这不起作用:

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

在那之后你会做任何你需要的加入。

答案 2 :(得分:0)

最终答案:

;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