如何在左连接中GROUP BY最大日期

时间:2017-11-27 12:55:49

标签: sql oracle group-by left-join greatest-n-per-group

我在Oracle DB中有三个表

House (
  id
)

Person (
  id,
  house_id
)

Bill (
  id,
  date,
  amount,
  person_id
)

如果房屋ID存在的话,我需要获得最后账单中的人员ID和金额。最后一个账单是具有最早日期字段的账单。 我可以通过这种方式获得它:

SELECT
 p.id,
 b.amount
FROM Person p
LEFT JOIN 
(SELECT amount FROM Bill WHERE date =
 (SELECT MAX(date) FROM Bill b1 WHERE person_id = 1)
) b ON b.person_id = p.id 
WHERE p.id = 1;

我可以通过房屋ID获取最新账单金额的人员ID列表吗?

示例数据:

House(id:1)
House(id:2)

Person(id:1, house_id:1)
Person(id:2, house_id:1)
Person(id:3, house_id:2)

Bill(id:1, date:01-11-2011, amount:100, person_id:1)
Bill(id:2, date:01-11-2012, amount:200, person_id:1)
Bill(id:3, date:01-11-2011, amount:90, person_id:2)
Bill(id:4, date:01-11-2012, amount:10, person_id:2)
Bill(id:5, date:01-11-2011, amount:190, person_id:3)

由house_id = 1选择的结果:

person_id:1, amount:200
person_id:2, amount:10

1 个答案:

答案 0 :(得分:1)

您可以通过聚合执行此操作:

select p.person_id,
       max(b.amount) keep (dense_rank first order by b.date desc) as most_recent_amount
from bill b join
     person p
     on b.person_id = p.id
where p.house_id = 1
group by p.person_id;