2013-02-15 65 views
0

我試圖從線程表中返回線程中的最新5個主題。然後,我還需要加入主題表以將topic_name +從線程表連接返回到作者表並返回作者姓名。SELECT distinct distinct top 5 Topic_ID,來自tblThread的Thread_ID ORDER BY Thread_ID DESC

如果一個主題出現在最近的X帖子中,我只希望最近的(最高)線程ID信息的次數。

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

剛剛如下

topic_id返回最近5倍線程ID的 - THREAD_ID

852 - 2905

852 - 2904,

850 - 2903,

937 - 2902,

937 - 2901

我想回到 852 - 2905 +等領域,主題名稱,作者姓名

850 - 2903 + ..

937 - 2902 + ...

&接下來的兩個主題ID的

感謝提前:)

+0

你或許應該抓住相應的線程ID與一個GROUP BY的話題,和MAX的線程ID,由線程ID DESC排序,並限制爲5。然後查詢線程與他們的ID在前一集。對不起,我沒有時間創建工作查詢,這只是一個想法。 – 2013-02-15 16:24:47

回答

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 
+0

嗨Lamak,不知道你是如何想出了,但它與適當的表名的作品,由:) – csbchris 2013-02-15 17:11:17

0

這會不會工作:

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

你會做什麼加入之後你需要。

+0

字段順序Thanks.When我填補了這一點來: – csbchris 2013-02-15 16:49:29

+0

選擇前5 tblThread.Topic_ID,MAX(tblThread.Thread_ID)AS線程ID,tblTopic.Subject FROM(tblThread INNER JOIN tblTopic ON tblThread.Topic_ID = tblTopic.Topic_ID)INNER JOIN tblAuthor ON tblThread.Author_ID = tblAuthor.Author_ID GROUP BY tblThread.Topic_ID,tblTopic.Subject ORDER BY線程ID DESC; – csbchris 2013-02-15 16:49:46

+0

它正確返回但沒有作者姓名。當我將「tblAuthor.Username」添加到第一行時,出現錯誤「Column'tblAuthor.Username'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。」但是當我將它添加到組中時,我得到不正確的結果。有任何想法嗎? – csbchris 2013-02-15 16:52:00

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