显示具有最新时间戳的单行

时间:2015-02-13 15:15:49

标签: sql-server-2008

使用SQL Server 2008,我试图想出一种在这里只显示一行的方法,它显示两个时间戳中较大或最近的一行。没有按'吨'必须匹配当前月份。只是最近的一个。如果有两个单独的列,而不是单个列的两行,我知道如何做到这一点。这是一个示例数据:

row Reader  Building    Timestamp       LockOut   Badge ID  Employee
1   5348      T        01/09/2015 19:08    N       F51184   35229934
2   5348      T        02/10/2015 18:23    N       F53629   38904421

我在Reader和Building上过滤

 SELECT 
 [Reader]
,[Building]
,[Timestamp]
,[LockOut]
,[Badge ID]
,[Employee] 
FROM [Security_Sequence]
WHERE Reader = ‘5384’ AND Building = ‘T’

预期产出

row Reader  Building    Timestamp       LockOut   Badge ID  Employee
2   5348      T        02/10/2015 18:23    N       F53629   38904421

1 个答案:

答案 0 :(得分:1)

如果您想要最新日期的记录

,请尝试此操作
SELECT TOP 1
 [Reader]
,[Building]
,[Timestamp]
,[LockOut]
,[Badge ID]
,[Employee] 
FROM [Security_Sequence]
WHERE Reader = ‘5384’ AND Building = ‘T’
ORDER BY [Timestamp] DESC

如果您想为每个ReaderBuilding选择最新日期,可以使用以下代码

;WITH CTE AS
( 
     SELECT ROW_NUMBER() OVER(PARTITION BY Reader,Building ORDER BY [Timestamp] DESC) RNO,
     [Reader]
    ,[Building]
    ,[Timestamp]
    ,[LockOut]
    ,[Badge ID]
    ,[Employee] 
     FROM [Security_Sequence]         
)
SELECT 
     [Reader]
    ,[Building]
    ,[Timestamp]
    ,[LockOut]
    ,[Badge ID]
    ,[Employee] 
     FROM [Security_Sequence]
WHERE RNO = 1