2014-09-01 112 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