简体   繁体   中英

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM