SQL Server:CTE,如何获取最后一个行号

时间:2011-01-27 07:46:52

标签: sql sql-server sql-server-2008

我有这样的CTE:

;WITH Lastdt AS
(
    SELECT database_name, backup_finish_date,
    ROW_NUMBER() OVER (PARTITION BY database_name ORDER BY backup_finish_date, database_name) AS 'RowNumber'
    FROM bckHist
) 
SELECT database_name, backup_finish_date
FROM Lastdt
WHERE RowNumber = '7'

如何从查询中获取最高编号的最后一行(替换硬编码的7)?

4 个答案:

答案 0 :(得分:2)

我认为这很容易......

;WITH Lastdt AS
(
    SELECT database_name, backup_finish_date,
    ROW_NUMBER() OVER (PARTITION BY database_name ORDER BY backup_finish_date desc, database_name) AS 'RowNumber'
    FROM bckHist
) 
SELECT database_name, backup_finish_date
FROM Lastdt
WHERE RowNumber = '1'

答案 1 :(得分:2)

如果你真的只需要最后一行(来自你的查询)那么它甚至更简单(对于给定的情况):


select database_name, max(backup_finish_date)
from bckHist
group by database_name

答案 2 :(得分:1)

试试这个:

;WITH Lastdt AS
(
    SELECT database_name, backup_finish_date,
    ROW_NUMBER() OVER (PARTITION BY database_name ORDER BY backup_finish_date, database_name) AS 'RowNumber'
    FROM bckHist
) 
SELECT TOP 1 
   database_name, backup_finish_date
FROM Lastdt
ORDER BY RowNumber DESC

基本上命令RowNumber降序(最大的第一个),然后只选择第一个。

答案 3 :(得分:0)

从bckHist中选择数据库名称,backup_finish_date,其中行号=(从bckHist中选择SELECT MAX(行号))