如何根据多行值选择不同的记录?

问题描述 投票:0回答:2

我有一张桌子

CREATE TABLE event
  uuid character varying(50),
  created timestamp without time zone DEFAULT now(),
  event_type character varying(50))

数据就是这样的

enter image description here

我需要获取每个uuid的'NotSaved'或'Saved'的最新event_type,例如uuid_1234,Saved和uuid_1235,NotSaved。我尝试使用distinct,subquery和max,但没有给出正确的结果

sql postgresql
2个回答
0
投票

使用row_number()

select * from      
 (
  select *,row_number() over(partition by uuid order by createdtimestamp desc) rn
 from event
) a where a.rn=1

以下也有用

 SELECT DISTINCT ON (uuid ) 
    uuid , createdtimestamp 
FROM event
ORDER BY event_timestamp DESC 

0
投票

一种方法是将表连接到自身。首先,创建select语句以提取uuid和指定所需事件类型的最新创建日期。

select uuid, max(created)
from event
where event_type in ('NotSaved', 'Saved')

请注意,我们无法在此语句中获取event_type列(或任何其他列)。只有uuid和最大创建。

然后,将此select语句用作“内联表”,将事件表连接到它以获取其余列。

select distinct e.uuid, e.created, e.event_type
from event e
inner join (select uuid, max(created)
            from event
            where event_type in ('NotSaved', 'Saved')) maxe
on e.uuid = maxe.uuid and e.created = maxe.created;

我们给内联表一个别名maxe,因为它实际上并不存在,我们需要一种方法来引用它。事件表的别名e只是为了方便,它使连接条件更容易键入和读取。

© www.soinside.com 2019 - 2024. All rights reserved.