I'm sitting at the following problem: I'm writing a view where I join several tables to a person table. And I now trying to join the partners table but I only need the historical last valid partner row:
partners table:
id,
name,
married_at,
divorced_at,
died_at,
someone_id
As you can see it's about partners you are/were married with. Someone can have only one partner at a time, but several partners in history. So the last partner of someone (someone_id) may be:
- alive and still married
- alive but divorced
- dead "but still married" (so someone is the widower)
I need to find ONLY the last partner row for someone.
What I got so far:
select *
from someone_table s
left join partners p on (p.someone_id = s.id and (p.divorced_at is null and p.died_at is null) )
But this - obvious as it is - gives me only partners who are still alive and still married. Sure these partners are the last partners of someone but all other "someones" whos last partner is divorced or dead won't be in the result of the statement. How do I get the other ones and only one row for each someone?
I also tried a select-statement as table and using of rownum
select *
from someone s,
(select * from partners p where p.someone_id = s.id and ROWNUM = 1 order by p.married_at)
But this statement always fails with an "invalied identifier s.id" error
Note: The table structure is fixed and can't be changed. DBMS is oracle.
Thanks in advance
edit: sample data
partners_table
╔════╦═════════╦════════════╦═════════════╦════════════╦════════════╗
║ id ║ name ║ married_at ║ divorced_at ║ died_at ║ someone_id ║
╠════╬═════════╬════════════╬═════════════╬════════════╬════════════╣
║ 1 ║ partner ║ 01.01.2000 ║ ║ ║ 12 ║
║ 2 ║ honey1 ║ 15.01.2000 ║ 15.01.2001 ║ ║ 15 ║
║ 3 ║ honey2 ║ 16.02.2001 ║ ║ ║ 15 ║
║ 4 ║ beauty ║ 23.03.2005 ║ ║ 25.03.2005 ║ 16 ║
║ 5 ║ lady1 ║ 11.11.2000 ║ 11.12.2000 ║ ║ 20 ║
║ 6 ║ lady2 ║ 12.12.2000 ║ 01.01.2001 ║ ║ 20 ║
║ 7 ║ lady3 ║ 02.02.2001 ║ ║ 04.02.2004 ║ 20 ║
║ 8 ║ lady4 ║ 05.05.2005 ║ ║ ║ 20 ║
║ 9 ║ mate ║ 23.06.2003 ║ 12.12.2009 ║ ║ 25 ║
╚════╩═════════╩════════════╩═════════════╩════════════╩════════════╝
last historical rows would be:
╔════╦═════════╦════════════╦═════════════╦════════════╦════════════╗
║ id ║ name ║ married_at ║ divorced_at ║ died_at ║ someone_id ║
╠════╬═════════╬════════════╬═════════════╬════════════╬════════════╣
║ 1 ║ partner ║ 01.01.2000 ║ ║ ║ 12 ║
║ 3 ║ honey2 ║ 16.02.2001 ║ ║ ║ 15 ║
║ 4 ║ beauty ║ 23.03.2005 ║ ║ 25.03.2005 ║ 16 ║
║ 8 ║ lady4 ║ 05.05.2005 ║ ║ ║ 20 ║
║ 9 ║ mate ║ 23.06.2003 ║ 12.12.2009 ║ ║ 25 ║
╚════╩═════════╩════════════╩═════════════╩════════════╩════════════╝