首先使用最新时间戳选择distinct的SQL查询

时间:2012-03-26 05:18:52

标签: sql distinct

我有一个包含三列的mysql表:用户名,位置,时间戳。这基本上是用户活动的日志,记录了他们所处的位置以及他们在那里的时间。

我想要做的是选择一个不同的用户名+位置,其中只提供最新项目(按时间戳)。

所以说该表包括:

tom roomone 2011-3-25 10:45:00
tom roomtwo 2011-3-25 09:00:00
tom roomtwo 2011-3-25 08:30:00
pam roomone 3011-3-25 07:20:23

我希望只选择这些:

tom roomone 2011-3-25 10:45:00
tom roomtwo 2011-3-25 09:00:00

2 个答案:

答案 0 :(得分:20)

使用table1作为您的表名尝试以下查询:

select username, location, max(timestamp) from table1
group by  username, location

答案 1 :(得分:1)

这个答案实际上并不能保证其他列与用户名/时间戳具有相同的记录,但以下内容(使用子查询)。

select t1.*
from (
  select ForeignKeyId,AttributeName, max(Created) AS MaxCreated
  from  YourTable
  group by ForeignKeyId,AttributeName
) t2
join YourTable t1
on t2.ForeignKeyId = t1.ForeignKeyId
and t2.AttributeName = t1.AttributeName
and t2.MaxCreated = t1.Created

答案发现于:

Select distinct most recent