[英]postgres / sql self join comparing rows
I have the following example table我有以下示例表
id, label, reason, timestamp
7, 123, ok, 10:50:01
6, 124, reject, 10:53:01
5, 123, reject, 10:30:02
4, 124, ok, 10:30:01
I'd like to get the rows whereby the if the label's last record (latest timestamp) is an ok we display it in the results but if there was a reject we don't.我想获取如果标签的最后一条记录(最新时间戳)是可以的行,我们会在结果中显示它,但如果有拒绝,我们不会。
eg例如
7, 123, ok, 10:50:01
It should be simple but I'm really having issues.这应该很简单,但我真的有问题。 Can someone assist?
有人可以帮忙吗? Thanks in advance.
提前致谢。
I would suggest distinct on
:我建议在以下方面
distinct on
:
select t.*
from (select distinct on (label) t.*
from t
order by label, timestamp desc
) t
where reason = 'ok';
You can also do this as:你也可以这样做:
select t.*
from t
where t.timestamp = (select max(t2.timestamp)
from t t2
where t2.label = t.label
) and
t.reason = 'ok';
Here's your query.这是您的查询。
select t1.* from
(select row_number() over (order by timestamp desc) as rn
, id, label, reason, timestamp
from tableA) as t1
where t1.rn = 1 and t1.reason = 'ok'
We could use some exists logic here:我们可以在这里使用一些存在的逻辑:
SELECT id, label, reason, timestamp
FROM yourTable t1
WHERE
reason = 'ok' AND
NOT EXISTS (SELECT 1 FROM yourTable t2
WHERE t2.label = t1.label AND
t2.timestamp > t1.timestamp);
This assumes you want the matching single row with the latest timestamp.这假设您想要具有最新时间戳的匹配单行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.