使用两列排序查询结果

时间:2012-10-22 19:49:20

标签: sql sql-server

我有这张桌子:

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

3 个答案:

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

答案 1 :(得分:2)

您可以在CASE中使用ORDER BY

....
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

答案 2 :(得分:2)

如果您的DBMS具有窗口功能,那么这也将解决它:

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