我有这样的查询:

SELECT TOP 5
    CONVERT(varchar(15), CAST(Pout AS time), 100) AS 'OUT',
    CONVERT(varchar(15), CAST(pIn AS time), 100) AS 'IN',
    DATEDIFF(MINUTE, CONVERT(varchar(5), Pout, 108), CONVERT(varchar(5), pIn, 108)) AS [Total Used]
FROM
    loginfo
WHERE
    empid = 1001
    AND CONVERT(date, pDate) = '28/Nov/2016 2:45:00 PM'
    AND pOut IS NOT NULL
ORDER BY
    pOut


该查询工作正常,但是我不想显示前5条记录,我需要显示最近5条记录,我的意思是最后5条记录,但是我无法显示ORDER BY pout DESC,因为我想以正确的格式显示报告,但我只需要显示交易的最后5条记录,而无需使用降序

例如,如果我有10条记录的交易,我只想以正确的格式显示最后5条记录

最佳答案

使用ROW_NUMBER()代替:

SELECT * FROM (
    SELECT
          CONVERT(varchar(15), CAST(Pout AS time), 100) AS [OUT],
          CONVERT(varchar(15), CAST(pIn AS time), 100) AS [IN],
          DATEDIFF(MINUTE, CONVERT(varchar(5), Pout, 108),
          CONVERT(varchar(5), pIn, 108)) AS [Total Used],
          ROW_NUMBER() OVER(ORDER BY pOut DESC) as rnk
    FROM loginfo
    WHERE empid = 1001
      AND CONVERT(date, pDate) = '28/Nov/2016 2:45:00 PM'
      AND pOut IS NOT NULL) p
WHERE p.rnk <= 5
ORDER BY What_Ever_You_Want


或者,使用派生表:

SELECT * FROM (Your Current Query)
ORDER BY pOut ;

关于sql - 不使用desc在sql中显示最后5条记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40886526/

10-09 02:59