您的基本查询应写为:
SELECT N.Caption AS Server, AVG(A.Availability) AS Avg_Availability
FROM Nodes AS N
JOIN DailyNodeAvailability AS A ON (N.NodeID = A.NodeID)
WHERE DateTime > (GetDate()-7)
AND (N.Caption LIKE '%server1%' OR
N.Caption LIKE '%server2%' OR
N.Caption LIKE '%server3%'
)
GROUP BY N.Caption
这将为您提供一个列表,其中包含每个服务器名称以及该服务器在上周的平均可用性。
要获得具有最低平均可用性及其平均可用性的服务器名称,您必须将该查询视为更大查询的一部分。在标准 SQL 中有两种方法可以做到这一点:冗长且普遍可用,以及简洁但不太广泛可用。
冗长的方式最终将该查询作为子查询写出几次(因此,在开发查询时,在继续执行更复杂的查询之前,让第一个查询正确并经过测试至关重要):
SELECT m.server, m.avg_availability
FROM (SELECT N.Caption AS Server, AVG(A.Availability) AS Avg_Availability
FROM Nodes AS N
JOIN DailyNodeAvailability AS A ON (N.NodeID = A.NodeID)
WHERE DateTime > (GetDate()-7)
AND (N.Caption LIKE '%server1%' OR
N.Caption LIKE '%server2%' OR
N.Caption LIKE '%server3%'
)
GROUP BY N.Caption
) AS m
JOIN (SELECT MIN(y.avg_availability) AS min_availability
FROM (SELECT N.Caption AS Server, AVG(A.Availability) AS Avg_Availability
FROM Nodes AS N
JOIN DailyNodeAvailability AS A ON (N.NodeID = A.NodeID)
WHERE DateTime > (GetDate()-7)
AND (N.Caption LIKE '%server1%' OR
N.Caption LIKE '%server2%' OR
N.Caption LIKE '%server3%'
)
GROUP BY N.Caption
) AS Y
) AS x
ON x.min_availability = m.avg_availability
简洁的方法是使用公用表表达式,即 WITH 子句:
WITH AvgAvailability AS
(
SELECT N.Caption AS Server, AVG(A.Availability) AS Avg_Availability
FROM Nodes AS N
JOIN DailyNodeAvailability AS A ON (N.NodeID = A.NodeID)
WHERE DateTime > (GetDate()-7)
AND (N.Caption LIKE '%server1%' OR
N.Caption LIKE '%server2%' OR
N.Caption LIKE '%server3%'
)
GROUP BY N.Caption
)
SELECT A.Server, A.Avg_Availabilty
FROM AvgAvailability AS A
JOIN (SELECT MIN(Avg_Availability) AS Min_Availability
FROM AvgAvailability
) AS M
ON A.Avg_Availability = M.Min_Availability
(未经测试的语法。)我不确定 MS SQL Server 中是否提供简洁选项。