按最新日期时间选择行

时间:2014-11-20 22:31:48

标签: sql sql-server sql-server-2008 datetime

我有以下视图,它从PERFMON创建的原始表中提取行。每60秒插入一行。

SELECT        
    dbo.CounterDetails.MachineName, dbo.CounterDetails.ObjectName, 
    dbo.CounterDetails.CounterName, dbo.CounterDetails.InstanceName, 
    dbo.CounterData.CounterValue, CONVERT(DATETIME, CONVERT(VARCHAR(16), 
    dbo.CounterData.CounterDateTime)) AS Date, dbo.CounterData.GUID
FROM            
    dbo.CounterData 
INNER JOIN
    dbo.CounterDetails ON dbo.CounterData.CounterID = dbo.CounterDetails.CounterID 
INNER JOIN
    dbo.DisplayToID ON dbo.CounterData.GUID = dbo.DisplayToID.GUID

如果选择*将返回,例如

    GUID    CounterID   RecordIndex CounterDateTime CounterValue    FirstValueA FirstValueB SecondValueA    SecondValueB    MultiCount
    362035A1-50A6-4F91-9423-82DCB5DED11B    1   1   2014-11-20 12:35:30.635 7459    7459    0   0   0   1
...
...
...

    GUID    CounterID   RecordIndex CounterDateTime CounterValue    FirstValueA FirstValueB SecondValueA    SecondValueB    MultiCount
    362035A1-50A6-4F91-9423-82DCB5DED11B    115 283 2014-11-20 17:22:13.424 0   0   0   0   0   1

我正在尝试从基于Web的应用程序的DATE值(DateTime)获取视图中的最新行,其中我只想在视图中显示最近(最后)的行。我已经尝试了很多东西,这是最新的,我尝试过的所有东西都给了我所有的行。甚至可以将查询限制为最后一次插入的行(或者甚至更复杂,查找执行时小于60秒的任何时间戳)。

SELECT 
    CounterValue , MachineName, ObjectName, CounterName,[Date]
FROM 
    [dbo].[PerfView] A
WHERE 
    ObjectName = 'Network Interface' 
    AND CounterName = 'Bytes Total/sec' 
    AND CounterValue <> 0 
    AND MachineName = '\\******** 
    AND [Date] = (SELECT MAX([Date]) 
                  FROM [dbo].[PerfView] B 
                  WHERE a.CounterValue = b.CounterValue)

2 个答案:

答案 0 :(得分:2)

这将为您提供最新记录:

SELECT top 1 CounterValue , MachineName, ObjectName, CounterName,[Date]
 FROM [dbo].[PerfView] A
 Where ObjectName = 'Network Interface' 
 and CounterName = 'Bytes Total/sec' 
 and CounterValue <>0 
 and MachineName = '\\******** 
order by [date] desc

如果您想在过去60秒内完成记录,请尝试:

SELECT CounterValue , MachineName, ObjectName, CounterName,[Date]
 FROM [dbo].[PerfView] A
 Where ObjectName = 'Network Interface' 
 and CounterName = 'Bytes Total/sec' 
 and CounterValue <>0 
 and MachineName = '\\******** 
 and [date] between dateadd(minute, -1, getdate()) and getdate()

答案 1 :(得分:0)

@tpcolson,

可能有很多方法可以做到这一点。 一种方式是@paqogomez建议的。那会给你你想要的东西。 另一种方法是使用rowcount。 设置RowCount 1,然后运行不带顶部1的查询。它也会给你相同的结果。

如果您使用的是sql server 2012,则另一种方法适用。有一个offset fetch子句。 订购后:

offset 0 rows fetch next 1 rows only

希望它会对你有所帮助。