SQL选择联接表上的最新记录

时间:2019-12-19 20:05:55

标签: sql database postgresql

我想检索用户最后一次纳税的财产。

有两个表person_propertiesproperty_taxes

person_properties
---------
person_id
property_id

property_taxes
---------
property_id
year

到目前为止我尝试过的事情:

SELECT pp.person_id, MAX(pt.year) 
FROM property_taxes pt
JOIN person_properties pp ON pt.property_id = pp.property_id
GROUP BY pp.person_id

这给了我person_id的最大值。 但是我实际上需要property_id,即用户最后支付的财产。

如果我将pp.person_id替换为pp.property_id,那么我当然会获得所有属性,而不是按人员分组,这会排除具有多个属性的用户。

有什么小小的调整可以帮助我获得理想的结果吗?

2 个答案:

答案 0 :(得分:4)

DISTINCT ON可能会做您想要的?

SELECT DISTINCT ON (pp.person_id)
       *
       FROM property_taxes pt
            INNER JOIN person_properties pp
                       ON pp.property_id = pt.property_id
       ORDER BY pp.person_id ASC,
                pt.year DESC;

答案 1 :(得分:1)

类似的东西

SELECT
    pt.property_id,
    pt.year
FROM
    property_taxes pt,
    person_properties pp,
    (
        SELECT
            pp.person_id p,
            MAX(pt.year) y,
        FROM
            property_taxes pt
        JOIN person_properties pp ON pt.property_id = pp.property_id
        GROUP BY pp.person_id
    ) sub
WHERE
    pt.property_id=pp.property_id AND
    pp.person_id=sub.p AND
    pt.year=sub.y