I want to create a view who gives me the grandchildren of the oldest person who has some. And the problem is that I can't find a way to translate in sql the phrase : "who has some".
I work in only one table which is pretty basic :
Person : number(type number), lastname, firstname, dateofbirth, gender, mother(type number), father(type number).
This is what I tried to do :
I tried to create a view who gives me the oldest person who has grandchildrens (but this is not what is done here)
CREATE OR REPLACE
VIEW oldestone
AS SELECT number FROM persons
WHERE (sysdate-dateofbirth)/365 >= ALL
(SELECT (sysdate-dateofbirth)/365 FROM persons)
AND EXISTS (SELECT * FROM persons
WHERE level=3
START WITH number = number
CONNECT BY PRIOR number = father OR PRIOR numero = mother);
And with the number of the first view I can get the grandchildren :
CREATE OR REPLACE
VIEW grandchildren
AS SELECT firstname,lastname FROM persons
WHERE level=3
START WITH number = (SELECT number FROM oldestone)
CONNECT BY PRIOR number = father OR PRIOR number = mother;
The problem is I know I'm not translating : the grandchildren of the oldest person who has some. Because in my first view when i wrote number = number I want to refer to the number of my select clause line 3 but i know it's not the case.
Thanks in advance for you help guys !
Chris.
If you reverse the direction to read "up" the family tree, rather than "down", you can go from grandchildren to their parents and then to the grandparents. As you do so, in the innermost subquery, you can "remember" the grandchildren's names with the
connect_by_root()
operator, and associate them with the dates of birth of their ancestors at different levels (their own dob's at level 1, their parents' dob's at level 2, their grandparents' dob's at level 3).In the intermediate subquery I select rows produced by the hierarchical query at level 3 - that will show the dates of birth of grandparents. I use an analytic function to record the minimum date of birth in the same query. (You don't need "age" - "oldest" means earliest date of birth!)
I wrote the query as economically as possible, at each stage keeping just the columns needed to produce the required result (the names of the grandchildren of the oldest grandparents); as you select the sub-subquery and the intermediate subquery and run them separately, to understand how this works, you may want to add more columns just to see what's going on.
I created some very simple test data in a WITH clause (not part of the solution); you may want to test with more interesting inputs. Good luck!