在多个条目中选择最新行

时间:2016-12-15 13:00:59

标签: sql sql-server

我有一张包含以下数据的表格。

enter image description here

现在我想根据每个Servername和Instance名称的每个数据库选择最新DateAdded的数据。

预期数据

enter image description here

3 个答案:

答案 0 :(得分:0)

尝试这种方式:

select
Database ,
Servername,
max(dateadded)
from table_db
group by Database ,Servername

答案 1 :(得分:0)

试试这个:

select serverName, 
       InstanceName, 
       DBName, 
       RecoveryModel,
       DateAdded, 
       LastBackupDate, 
       LastDifferentialBackupDate, 
       LastLogBackupDate
from ( 
       select serverName, 
              InstanceName, 
              DBName, 
              RecoveryModel,
              DateAdded, 
              LastBackupDate, 
              LastDifferentialBackupDate, 
              LastLogBackupDate, 
              row_number() over(partition by serverName,DBname order by DateAdded desc) as rn 
      from DB.databaseinfo 
                            ) X 
      where X.rn=1 
      order by X.serverName,X.InstanceName,DBName

答案 2 :(得分:-1)

select      *

from       (select      *
                       ,row_number ( ) over 
                       (
                            partition by  Servername,InstanceName,DBName
                            order by      DateAdded desc
                        ) as rn

            from        MyTable 
            ) t

where       rn = 1
;