获取最后5行但按顺序创建

时间:2013-02-02 11:32:20

标签: sql sql-server

我有一张表格,其中包含以下信息:

mesID是我的身份种子

mesID | ToUser | FromUser | DateTime
-------------------------------------
91    | jason  | krissy   | 1/18/2013 12:10:23 PM
92    | jason  | krissy   | 1/18/2013 12:20:38 PM
93    | jason  | krissy   | 1/18/2013 12:35:14 PM
94    | jason  | krissy   | 1/18/2013 12:20:38 PM
95    | jason  | krissy   | 1/18/2013 12:35:14 PM
98    | jason  | krissy   | 1/18/2013 12:10:23 PM
101   | jason  | krissy   | 1/18/2013 12:20:38 PM
104   | jason  | krissy   | 1/18/2013 12:35:14 PM
109   | jason  | krissy   | 1/18/2013 12:54:11 PM

现在请记住,我有超过60条消息,它们是较低的mesID然后是98.我想要做的只是获取最后5条消息,但保持原始顺序从最旧到最新消息返回(mesID = 1显然是最古老的。)

从逻辑上讲,我认为我会获得前5名的回报,并由DESC通过mesID订购。然后在返回5之后再通过mesID AESC对它们进行重新排序,但我不知道如何做到这一点。

所以最终结果我会得到类似......

95    | jason  | krissy   | 1/18/2013 12:35:14 PM
98    | jason  | krissy   | 1/18/2013 12:10:23 PM
101   | jason  | krissy   | 1/18/2013 12:20:38 PM
104   | jason  | krissy   | 1/18/2013 12:35:14 PM
109   | jason  | krissy   | 1/18/2013 12:54:11 PM

3 个答案:

答案 0 :(得分:4)

SELECT *
FROM   (
           SELECT TOP 5 *
           FROM   TABLE
           ORDER BY
                  mesID DESC
       ) t
ORDER BY
       t.mesID

答案 1 :(得分:3)

执行子查询:

SELECT *
FROM   TABLE
WHERE  mesid IN (SELECT TOP 5 mesid
                 FROM   TABLE
                 WHERE ToUser like '%krissy%' or FromUser like '%krissy%'  
                 ORDER BY
                        mesid DESC)
ORDER BY
       mesid ASC

答案 2 :(得分:1)

这将获得最新的5,假设每个用户都有许多toUSer和FromUser 的记录。

WITH recordList
AS
(
    SELECT mesID, ToUSer, FromUser, DateTime,
            ROW_NUMBER() OVER (PARTITION BY ToUSer, FromUser
                                ORDER BY mesID DESC) rn
    FROM tableName
)
SELECT mesID, ToUSer, FromUser, DateTime
FROM recordList
WHERE rn <= 5
ORDER BY mesID