Postgresql 从SQL on JOIN中的第二个表中获取最新结果
表aPostgresql 从SQL on JOIN中的第二个表中获取最新结果,postgresql,greatest-n-per-group,Postgresql,Greatest N Per Group,表a ID Status NAME --------------------------------- 1 pending RAM 2 pending SHYAM 3 pending JULIEN 4 pending KRISH 5 pending Jenkins 6 accepted K8s 表b ID
ID Status NAME
---------------------------------
1 pending RAM
2 pending SHYAM
3 pending JULIEN
4 pending KRISH
5 pending Jenkins
6 accepted K8s
表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
预期结果:
NAME values
--------------
RAM L2
SHYAM L1
JULIEN ""
KRISH ""
Jenkins ""
K8s ""
查询:我尝试了下面的查询,但对我无效
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';
您可以使用相关子查询进行筛选:
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'
有两个问题:
DISTINCT ON
,获取每个用户的最新条目:有SQL来显示尝试吗?
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;