2012-10-22 281 views
4

我有這個表:排序的查詢結果有兩列

Reply_ID | Fk_Post_ID 
    10 | 5 
    9  | 6 
    8  | 5 
    7  | 9 
    6  | 5 
    5  | 9 
    4  | 7 

我需要一個查詢以下順序模式檢索記錄。它搜索具有最高reply_ID的記錄,然後檢索具有相同Fk_Post_ID的所有記錄。是這樣的:

Reply_ID | Fk_Post_ID 
    10 | 5 
    8  | 5 
    6  | 5 
    9  | 6 
    7  | 9 
    5  | 9 
    4  | 7 
+0

我認爲,如果你用行延伸的例子(5,9)和(4,7),這將是更清楚你在找什麼。 – Laurence

回答

5
CREATE TABLE #YourTable (
    Reply_ID INT, 
    fk_Post_ID INT 
) 

INSERT INTO #YourTable VALUES (10, 5) 
INSERT INTO #YourTable VALUES (9, 6) 
INSERT INTO #YourTable VALUES (8, 5) 
INSERT INTO #YourTable VALUES (7, 9) 
INSERT INTO #YourTable VALUES (6, 5) 


SELECT 
    t1.Reply_ID, 
    t1.fk_Post_ID 
FROM 
    #YourTable t1 JOIN (
    SELECT 
     MAX(Reply_ID) AS Max_Reply_ID, 
     fk_Post_ID 
    FROM #YourTable 
    GROUP BY fk_Post_ID 
) t2 ON t2.fk_Post_ID = t1.fk_Post_ID 
ORDER BY 
    t2.Max_Reply_ID DESC, 
    t1.Reply_ID DESC 

Sql Fiddle Here

+0

是的相同的結果。它很好地工作。所以它是與max()的連接。我在where子句中嘗試了子查詢,但沒有工作。謝謝:) – Roobah

2

你可以在ORDER BY使用CASE

.... 
ORDER BY CASE WHEN Fk_Post_ID=(
        SELECT MIN(Fk_Post_ID) 
        FROM dbo.Table 
        WHERE Reply_ID=(SELECT MAX(Reply_ID)FROM dbo.Table) 
       ) THEN 0 ELSE 1 END ASC 
, Reply_ID DESC 
, Fk_Post_ID ASC 

這裏的小提琴:http://sqlfiddle.com/#!3/45f20/7/0

+0

我試過了,但沒有奏效。查詢結果就像(order by reply_id,fk_post_id) – Roobah

+0

@Roobah:你見過[** fiddle **](http://sqlfiddle.com/#!3/45f20/7/0)嗎? –

+0

是的。但奇怪的是它不會給我在我的數據庫服務器 – Roobah

2

如果你的DBMS有窗函數那麼這也將解決我T:

Select 
    Reply_ID, 
    FK_Post_ID 
From 
    yourTable a 
Order By 
    Max(Reply_ID) Over (Partition By FK_Post_ID) Desc, 
    Reply_ID Desc 

http://sqlfiddle.com/#!3/4be0c/9/0

+0

是的,我有。它也有效。謝謝。 – Roobah