如何为不同的列值选择最新记录?

时间:2019-02-20 07:52:57

标签: sql mariadb groupwise-maximum

在我的数据库中,我的个人资料ID的状态也带有时间戳。我想使用查询获取每个配置文件的最新状态。我该怎么做最简单的方法?

所以用于:

Id      Profile  Timestamp
-------------------------
1        1       1550588089
2        1       1550588099
3        3       1550588183
4        4       1550588333
5        4       1550588534
6        4       1550588377

我想拥有

Id      Timestamp
-------------------------
2       1550588099
3       1550588183
5       1550588534

3 个答案:

答案 0 :(得分:1)

您可以使用相关子查询

DEMO

select id as status, Timestamp
from tablename a where timestamp in (select max(timestamp) from tablename b where a.profile=b.profile )

输出:

tatus   Timestamps
2       1550588099
3       1550588183
5       1550588534

或者您可以使用row_number()

select * from 
(
select *, row_number() over(partition by profile order by timestamp desc) as rn
from tablename
)A where rn=1

答案 1 :(得分:1)

使用支持最大dbms的row_number()

 select * from 
(
 select *,row_number() over(partition by Id order by timestamp desc) rn
 from table
) t where t.rn=1

答案 2 :(得分:0)

此查询:

select profile, max(timestamp) maxtimestamp 
from tablename
group by profile 

返回每个配置文件的所有最大时间戳。
因此,将其连接到主表即可满足您的需求:

select id, timestamp
from tablename t
inner join (
  select profile, max(timestamp) maxtimestamp 
  from tablename
  group by profile 
) g
on g.profile = t.profile and g.maxtimestamp = t.timestamp

请参见demo