如何select 不同列值的最新记录?
How to select the latest records for distinct column values?
在我的数据库中,我有配置文件 ID,其状态也有时间戳。我想使用查询获得每个配置文件的最新状态。我怎样才能以最简单的方式做到这一点?
所以f.e。对于:
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
可以使用关联子查询
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
使用支持最大 dbms
的 row_number()
select * from
(
select *,row_number() over(partition by Id order by timestamp desc) rn
from table
) t where t.rn=1
这个查询:
select profile, max(timestamp) maxtimestamp
from tablename
group by profile
returns 每个配置文件的所有最大时间戳。
因此,您可以通过将其加入主 table:
来获得所需的内容
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
在我的数据库中,我有配置文件 ID,其状态也有时间戳。我想使用查询获得每个配置文件的最新状态。我怎样才能以最简单的方式做到这一点?
所以f.e。对于:
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
可以使用关联子查询
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
使用支持最大 dbms
的row_number()
select * from
(
select *,row_number() over(partition by Id order by timestamp desc) rn
from table
) t where t.rn=1
这个查询:
select profile, max(timestamp) maxtimestamp
from tablename
group by profile
returns 每个配置文件的所有最大时间戳。
因此,您可以通过将其加入主 table:
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