0

所以我正在研究数据库的视图。在此视图中,它需要显示一个人拥有的所有属性,并且只显示该属性的当前所有者。应该这样做的方式是查看 propertyID 的购买日期,并且只显示最近的一个。

这是我到目前为止的代码:

CREATE VIEW P_OWNERS_AND_PROPERTIES_V AS
SELECT P_OWNER.OWNERID, P_OWNER.LNAME, P_OWNER.FNAME, 
P_PURCHASE.PROPERTYID,P_PURCHASE.PURCHASEDATE
FROM P_OWNER LEFT JOIN P_PURCHASE
ON P_OWNER.OWNERID=P_PURCHASE.OWNERID
WHERE (P_PURCHASE.PURCHASEDATE = (SELECT MAX(P1.PURCHASEDATE) 
FROM P_PURCHASE P1 WHERE P1.OWNERID = P_PURCHASE.OWNERID)) 
OR (P_PURCHASE.PROPERTYID IS NULL);

任何帮助将非常感激。

编辑:清理代码。

4

1 回答 1

0

Here is what I would do:

Join p_owner and p_purchase via ownerid. This gives you a list where each owner is shown with the all the properties ever owned (i.e. a full listing of all purchases)

Then you add an analytic function rownum() where you partition by propteryid and order by purchasedate desc. This adds a number to each row, such that the latest purchase for each property gets a rownum()=1. Alias this column with something like "purchase_rank".

Purchase_rank tells you, for each purchase, if it was the latest, second-to-latest etc.

Then wrap the whole thing in another select, where you filter "where purchase_rank=1", and chose the columns you want to see.

In any case, don't shy away from analytic functions. They can be life-saving.

于 2013-04-25T07:14:05.437 回答