获取最新的不同记录

时间:2012-09-19 14:28:33

标签: sql sql-server-2008-r2

考虑下表:

User  CreatedDateTime   Quantity
----- ----------------- --------
Jim   2012-09-19 01:00  1
Jim   2012-09-19 02:00  5
Jim   2012-09-19 03:00  2
Bob   2012-09-19 02:00  2
Bob   2012-09-19 03:00  9
Bob   2012-09-19 05:00  1

哪个查询会返回每个CreatedDateTime的最新行(由User定义),以便我们可以确定关联的Quantity

即。以下记录

User  CreatedDateTime   Quantity
----- ----------------- --------
Jim   2012-09-19 03:00  2
Bob   2012-09-19 05:00  1

我们认为我们可以简单Group By UserCreatedDateTime并添加Having MessageCreationDateTime = MAX(.MessageCreationDateTime。当然这不起作用,因为Quantity之后Group By不可用。

5 个答案:

答案 0 :(得分:4)

由于您使用的是SQL Server,因此可以使用Window Function

SELECT [User], CreatedDateTime, Quantity
FROM
    (
        SELECT [User], CreatedDateTime, Quantity,
                ROW_NUMBER() OVER(PARTITION BY [User] ORDER BY CreatedDateTime DESC) as RowNum
        FROM tableName
    ) a
WHERE  a.RowNum = 1

SQLFiddle Demo

答案 1 :(得分:4)

;WITH x AS
(
  SELECT [User], CreatedDateTime, Quantity, 
   rn = ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY CreatedDateTime DESC)
  FROM dbo.table_name
)
SELECT [User], CreatedDateTime, Quantity
FROM x WHERE rn = 1;

答案 2 :(得分:1)

如果您无法使用窗口函数,则可以使用子查询:

select t1.[user], t2.mxdate, t1.quantity
from yourtable t1
inner join
(
    select [user], max(CreatedDateTime) mxdate
    from yourtable
    group by [user]
) t2
    on t1.[user]= t2.[user]
    and t1.CreatedDateTime = t2.mxdate

请参阅SQL Fiddle with Demo

答案 3 :(得分:0)

SELECT DISTINCT 
User, 
CreatedDateTime, 
Quantity
FROM 
YourTable
WHERE 
CreatedDateTime = 
(SELECT MAX(CreatedDateTime) FROM YourTable t WHERE t.User = YourTable.User)

答案 4 :(得分:0)

select * from <table_name> where CreatedDateTime in (select max(CreatedDateTime) from <table_name> group by user) group by user;