2014-09-01 114 views
0

我使用下面的MS SQL查詢SQL在SQL Server中選擇最新的記錄

SELECT Top(100) 
    DateTime, DisplayName, FullName,SampleValue 
FROM 
    OperationsManagerDW.dbo.vManagedEntity, 
    OperationsManagerDW.dbo.vPerformanceRule, 
    OperationsManagerDW.dbo.vPerformanceRuleInstance, 
    OperationsManagerDW.Perf.vPerfRaw 
WHERE 
    vPerfRaw.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId 
    AND vPerfRaw.PerformanceRuleInstanceRowId = vPerformanceRuleInstance.PerformanceRuleInstanceRowId 
    AND vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId 
    AND vPerformanceRule.ObjectName = 'Memory' 
    AND vPerformanceRule.CounterName = 'PercentMemoryUsed' 
ORDER BY 
    DateTime DESC,Displayname, FullName 

我收到此

DateTime      FullName SampleValue 
--------------------------------------------------------- 
01.09.2014 13:23:29.200 N17.DE1.LOC 162.007 
01.09.2014 13:18:29.217 N17.DE1.LOC 160.298 
01.09.2014 13:18:29.187 N17.DE1.LOC 159.816 
01.09.2014 13:14:24.973 X-OM01.DE1.LOC 285.489 
01.09.2014 13:09:24.930 X-OM01.DE1.LOC 304.142 
01.09.2014 12:58:29.323 N17.DE1.LOC 159.469 
01.09.2014 12:58:29.277 N17.DE1.LOC 159.671 
01.09.2014 12:34:38.157 DC1.DE1.LOC 40.221 

,但我只需要服務器的最新條目(見全名) :

01.09.2014 13:23:29.200 N17.DE1.LOC   162.007 
01.09.2014 13:14:24.973 X-OM01.DE1.LOC  285.489 
01.09.2014 12:34:38.157 DC1.DE1.LOC  40.221 

請幫助。 Regards

+0

您可以使用distinct語句。 – 2014-09-01 13:41:31

+0

@ R.T。 :似乎OP嘗試按FullName字段的一部分進行分組,例如'N17.DE1.LOC 162.007' - >'N17.DE1.LOC' – 2014-09-01 13:43:08

+0

[踢壞的惡習:使用舊式JOIN](http:// sqlblog。 com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx) - 舊式*逗號分隔的表*樣式列表應該爲** no更長時間使用**,而是建議使用** ANSI + ** SQL標準引入的ANSI JOIN **語法(大於** 20年前) – 2014-09-01 14:01:14

回答

4

您可以使用row_number函數。嘗試以下查詢。 我假設你需要每個零件名稱的最新記錄。

WITH data 
AS 
(
SELECT Top(100) DateTime, DisplayName, FullName,SampleValue, 
ROW_NUMBER() OVER(PARTITION BY FullName ORDER BY DATETIME DESC) AS rowNum 
FROM OperationsManagerDW.dbo.vManagedEntity, 
OperationsManagerDW.dbo.vPerformanceRule, 
OperationsManagerDW.dbo.vPerformanceRuleInstance, 
OperationsManagerDW.Perf.vPerfRaw 
WHERE vPerfRaw.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId 
AND vPerfRaw.PerformanceRuleInstanceRowId = vPerformanceRuleInstance.PerformanceRuleInstanceRowId 
AND vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId 
AND vPerformanceRule.ObjectName = 'Memory' 
AND vPerformanceRule.CounterName = 'PercentMemoryUsed' 

) 
SELECT * FROM data 
WHERE rowNum =1 
ORDER BY [DateTime] DESC,Displayname, FullName 
+0

謝謝你這個完美的作品! – 2014-09-01 15:16:15

+0

請不要忘記標記爲答案。 – 2014-09-01 16:02:16

0

作爲基蘭的替代品,你也可以使用子查詢來做到這一點,也可以使用連接使它更好的可讀性。

select [fields] from 
    (Select top(100) datetime, id 
    from table1 
    order by datetime desc) T 
inner join [other tables] 
    on [join condition] 
order by datetime desc, displayname, fullname 
+0

偉大的我會試試這個! – 2014-09-01 15:16:31