Skip to content
Advertisement

SQL Server: CTE, how to get last row number

I have a CTE like this:

;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'

How can I get last row with highest number from the query (replace hardcoded 7)?

Advertisement

Answer

If you really need only last row (from your query) then it even simpler (for given case):

select database_name, max(backup_finish_date)
from bckHist
group by database_name
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement