SQL Server。CTE,如何获取最后一行编号
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server。CTE,如何获取最后一行编号相关的知识,希望对你有一定的参考价值。
我有一个这样的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)?
答案
如果你真的只需要最后一行(从你的查询中),那么它甚至更简单(对于给定的情况)。
select database_name, max(backup_finish_date)
from bckHist
group by database_name
另一答案
我想这很简单...
;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'
另一答案
试试这个。
;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
降序(最大的先),只选取第一个。
另一答案
SELECT database_name, backup_finish_date FROM bckHist WHERE RowNumber = (SELECT MAX(RowNumber) FROM bckHist)
以上是关于SQL Server。CTE,如何获取最后一行编号的主要内容,如果未能解决你的问题,请参考以下文章
sql server使用cte递归查询获取树形的父节点/子节点