Skip to content
Advertisement

How to using oracle distinct and order siblings by at the same time?

the distinct broken the order siblings by,how can i use them at the same time? such as select distinct * from table xxx starts with … connect by id=pid order siblings by field here is the test sqls executed with different results

here is the table

Advertisement

Answer

You can use ORDER SIBLINGS BY in an inner query and then use ROW_NUMBER() analytic function to find the duplicates in an outer query and maintain the order using ORDER BY ROWNUM in that outer query:

Which, for the sample data:

Note: this has an added row so there is a path back to a previous branch in the hierarchy to create duplicate rows in the output.

Outputs:

ID PID ORDER_NUM
1 null 1
4 1 4
2 1 5
3 null 2
5 3 2
1 5 5

and maintains the order of the siblings from the hierarchical query.

db<>fiddle here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement