Consider the following table:
employer_id | supervisor_employer_ref | date_hired |
---|---|---|
22436 | NULL | 01/02/2006 |
37854 | 25558 | 07/12/2018 |
25558 | NULL | 10/16/2010 |
48796 | 25558 | 11/11/2015 |
28449 | 22436 | 08/14/2016 |
34663 | 25558 | 10/10/2019 |
45687 | 22436 | 04/12/2020 |
For some specific reason i have to order this table by the employer and then its supervised employers and order them by date_hired on an Oracle 12c DB. I'm aware this is not the most ideal way of making a database but for a specific reason I have to keep it this way.
Intended result:
employer_id | supervisor_employer_ref | date_hired |
---|---|---|
22436 | NULL | 01/02/2006 |
28449 | 22436 | 08/14/2016 |
45687 | 22436 | 04/12/2020 |
25558 | NULL | 10/16/2010 |
48796 | 25558 | 11/11/2015 |
37854 | 25558 | 07/12/2018 |
34663 | 25558 | 10/10/2019 |
45687 | 22436 | 04/12/2020 |
You want a hierarchical query and to use ORDER SIBLINGS BY
:
SELECT *
FROM table_name
START WITH
supervisor_employer_ref IS NULL
CONNECT BY
PRIOR employer_id = supervisor_employer_ref
ORDER SIBLINGS BY date_hired;
Which, for the sample data:
CREATE TABLE table_name (employer_id, supervisor_employer_ref, date_hired) AS
SELECT 22436, NULL, TO_DATE( '01/02/2006', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 37854, 25558, TO_DATE( '07/12/2018', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 25558, NULL, TO_DATE( '10/16/2010', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 48796, 25558, TO_DATE( '11/11/2015', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 28449, 22436, TO_DATE( '08/14/2016', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 34663, 25558, TO_DATE( '10/10/2019', 'MM/DD/YYYY' ) FROM DUAL UNION ALL
SELECT 45687, 22436, TO_DATE( '04/12/2020', 'MM/DD/YYYY' ) FROM DUAL;
Outputs:
EMPLOYER_ID SUPERVISOR_EMPLOYER_REF DATE_HIRED 22436 02-JAN-06 28449 22436 14-AUG-16 45687 22436 12-APR-20 25558 16-OCT-10 48796 25558 11-NOV-15 37854 25558 12-JUL-18 34663 25558 10-OCT-19
db<>fiddle here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.