在组中仅显示一行(最新)

时间:2017-08-13 11:56:13

标签: sql sql-server

我无法理解这一个。我需要以下查询只向我显示每个数据库的最新备份,无论它是差异还是完整的事实。

在我的情况下,查询为特定数据库呈现两行 - 一行用于最新的差异,一行用于最新的完整。

提前致谢。

SELECT A.server_name as Instance, B.name as Database_Name,
       ISNULL(Convert(char(19), max(backup_finish_date), 100), 'NEVER') as Backup_Date, case when type='D' then 'FULL' when type='I' then 'DIFFERENTIAL'when type='L' then 'LOG'end  as Backup_Type,
       'Succeeded' as Status
FROM master.dbo.sysdatabases B LEFT OUTER JOIN
     msdb.dbo.backupset A
     ON A.database_name = B.name
where B.name not in ('master', 'model', 'msdb', 'tempdb') and
      a.machine_name IS NOT NULL and type in ('D', 'I')
GROUP BY B.name, A.machine_name, A.server_name, A.type
ORDER BY B.name, Backup_Date desc, A.type;

1 个答案:

答案 0 :(得分:2)

您可以使用row_number过滤器,如下所示:

Select * from (
    SELECT A.server_name as Instance, B.name as Database_Name,
           ISNULL(Convert(char(19), max(backup_finish_date), 100), 'NEVER') as Backup_Date, case when type='D' then 'FULL' when type='I' then 'DIFFERENTIAL'when type='L' then 'LOG'end  as Backup_Type,
           'Succeeded' as Status,
           RowN = Row_Number() over(Partition by B.name, A.machine_name, A.server_name, A.type order by backup_finish_date desc)
    FROM master.dbo.sysdatabases B LEFT OUTER JOIN
         msdb.dbo.backupset A
         ON A.database_name = B.name
    where B.name not in ('master', 'model', 'msdb', 'tempdb') and
          a.machine_name IS NOT NULL and type in ('D', 'I')
) sq 
Where sq.RowN = 1
ORDER BY sq.name, sq.Backup_Date desc, sq.type