SQL查询:服务器和磁盘的最新服务器条目

时间:2016-02-24 16:28:16

标签: sql-server

我有一个每小时按磁盘存储服务器可用磁盘空间的数据库。

我的查询目前按以下格式获取:

Name        DriveSpace  Date        Time

Server1 F:  123123123   2016-02-24  07:00:00
Server2 F:  123123123   2016-02-24  07:00:00
Server3 F:  123123123   2016-02-24  07:00:00
Server1 G:  123123123   2016-02-24  07:00:00
Server2 G:  123123123   2016-02-24  07:00:00
Server3 G:  123123123   2016-02-24  07:00:00
Server1 H:  123123123   2016-02-24  07:00:00
Server2 H:  123123123   2016-02-24  07:00:00
Server3 H:  123123123   2016-02-24  07:00:00
Server1 F:  123123123   2016-02-24  12:00:00
Server2 F:  123123123   2016-02-24  12:00:00
Server3 F:  123123123   2016-02-24  12:00:00
Server1 G:  123123123   2016-02-24  12:00:00
Server2 G:  123123123   2016-02-24  12:00:00
Server3 G:  123123123   2016-02-24  12:00:00
Server1 H:  123123123   2016-02-24  12:00:00
Server2 H:  123123123   2016-02-24  12:00:00
Server3 H:  123123123   2016-02-24  12:00:00

我想得到以下内容:

Server1 F:  freespace   2016-02-24  12:00:00
Server1 G:  freespace   2016-02-24  12:00:00
Server1 H:  freespace   2016-02-24  12:00:00
Server2 F:  freespace   2016-02-24  12:00:00
Server2 G:  freespace   2016-02-24  12:00:00
Server2 H:  freespace   2016-02-24  12:00:00
Server3 F:  freespace   2016-02-24  12:00:00
Server3 G:  freespace   2016-02-24  12:00:00
Server3 H:  freespace   2016-02-24  12:00:00

基本上是这样的:

我想要每台服务器每个磁盘的最新条目。 所以服务器1,服务器2和服务器3的磁盘上的所有最新更新

1 个答案:

答案 0 :(得分:2)

您的专栏名称不清楚,因此我正在制作它们。您应该能够从我的代码中推断出真正的列名:

SELECT t1.*
FROM [Table] t1
INNER JOIN (
    SELECT ServerName, MAX(Timestamp) TS,
    FROM [Table]
    GROUP BY ServerName
) t2 ON t2.ServerName = t1.ServerName and t2.TS = t1.TimeStamp

或者,如果它可能有多个具有相同服务器和时间戳的记录:

WITH Keys As (
    SELECT ServerName, MAX(Timestamp) TS,
    FROM [Table]
    GROUP BY ServerName
)
SELECT v.*
FROM Keys t
CROSS APPLY (
     SELECT TOP 1 * 
     FROM [Table] u 
     WHERE u.ServerName = t.ServerName AND u.Timestamp = t.TS 
     ORDER BY FreeSpace
 ) v