Reputation: 81
table_a
ID Status NAME
---------------------------------
1 pending RAM
2 pending SHYAM
3 pending JULIEN
4 pending KRISH
5 pending Jenkins
6 accepted K8s
table_b
ID Values Datetime TYPE
---------------------------------------------
1 L1 2018-06-02 L
1 L2 2019-07-20 L
1 G1 2019-09-20 G
2 L1 2019-09-20 L
2 K1 2019-09-15 K
3 M1 2019-10-22 M
4 R1 2019-10-23 R
Expected result:
NAME values
--------------
RAM L2
SHYAM L1
JULIEN ""
KRISH ""
Jenkins ""
K8s ""
Query: I tried below query but it didn't work for me.
SELECT a.NAME,b.values
FROM table_a a
LEFT JOIN table_b b ON a.ID=b.ID
where a.Status ='pending'
and b.type='L';
Upvotes: 2
Views: 58
Reputation: 222402
You can filter with a correlated subquery:
select a.name, b.values
from table_a a
inner join table_b b
on a.id = b.id
and b.type='L'
and b.datetime = (
select max(b1.datetime)
from table_b b1
where b1.id = b.id
)
where a.status ='pending'
Upvotes: 0
Reputation: 6713
There are two issues:
DISTINCT ON
in postgres to get the latest entry for each user:select DISTINCT ON (name)
a.name, b.values
FROM table_a a
LEFT JOIN table_b b ON a.id = b.id AND b.type = 'L' and a.status = 'pending'
ORDER BY name, datetime desc;
Upvotes: 1