具有最新日期的SQL Server行

时间:2011-09-27 20:40:14

标签: sql-server

我有一张桌子:

EventLog (
    EventID (INT),
    UserID (VARCHAR(50),
    Event (NTEXT),
    EventDate(DateTime),
    DocuvmentID(INT)
)

我需要编写一个查询来获取最新的事件,一堆userId的日期时间将是

WHERE UserID IN ( 'john','tom'...etc)

我该怎么做?

3 个答案:

答案 0 :(得分:2)

SELECT y.UserID, y.Event, y.EventDate
    FROM (SELECT UserId, MAX(EventDate) AS MaxDate
              FROM YourTable
              WHERE UserId IN ('john','tom',...)
              GROUP BY UserId) t
        INNER JOIN YourTable y
            ON t.UserId = y.UserId
                AND t.MaxDate = y.EventDate

答案 1 :(得分:1)

使用简单的CTE:

;WITH LatestDates AS
(SELECT 
    EventID, UserID,
    Event, EventDate,
    DocumentID,
    ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY EventDate DESC) AS 'RowNum'
)
SELECT * 
FROM LatestDates
WHERE RowNum = 1 AND UserID IN (........)

这会按照某些条件对您的数据进行分区(我选择UserID作为选项 - 可能是您的其他选择),然后从1开始依次为每个组编号,按其他条件排序(此处:{{1} }) - 所以每个“分区”的最新事件都有EventDate DESC,这是我从CTE中选择的

答案 2 :(得分:0)

        select 
            UserID,
            MAX(EventDate) AS LatestEventDate
        from
            EventLog
        where
            UserID in ('john','tom')
        group by
            UserID