I have two tables in a master-detail relationship.
The structure is more or less as follows:
Master table:
MasterID, DetailID, date, ...
masterID1, detailID1, 2010/5/1, ....
masterID2, detailID1, 2008/6/14, ...
masterID3, detailID1, 2009/5/25, ...
masterID4, detailID2, 2008/7/24, ...
masterID5, detailID2, 2010/4/1, ...
masterID6, detailID4, 2008/9/16, ...
Details table:
DetailID, ...
detailID1, ...
detailID2, ...
detailID3, ...
detailID4, ...
I need to get all the records from the details table plus the LAST record from the master table (last by the date in the master table).
Like this:
detailID1, masterID1, 2010/5/1, ....
detailID2, masterID5, 2010/4/1, ...
detailID3, null, null, ...
detailID4, masterID6, 2008/9/16, ...
I have no idea how to do this.
Can anybody help me?
Thanks a lot.
Jan
What I’m doing here is dealing with ties. If you had two Master rows with the same DetailId and Date, I’m choosing the one with the highest MasterId.
Btw, this problem is significantly simpler if you have common table expressions (CTE). With a CTE you can do something like: