Question

I have a table with some data as follows

 Id | Title  | Category
 --  -----     --------
  1   Beans    Food
  2   Pizza    Food
  3   SQL      Book
  4   Avatar   Movie
  5   Oracle   Book

I would like to organize this kind of table data in the form of a TREE with root node as Category.

Food
  Beans
  Pizza
Book
  SQL
  Oracle
Movie
  Avatar

Could you suggest a hierarchical query. I tried few, but could not get the desired result.

UPDATE realspirituals

Setup a fiddle here, if you want to try

Était-ce utile?

La solution

This could be one solution

with tab as (select distinct category title, null parent from test
          union all 
         select title, category from test)
select lpad(' ', (level * 2 - 1), '-' ) ||  title as title
  from tab
  start with parent is null
connect by prior title = parent;

SqlFiddle

Autres conseils

Try this query:

SELECT CASE
  WHEN title IS NULL THEN category
  ELSE '- ' || title
END category_title
FROM (
  SELECT title, category FROM table
  union all
  SELECT DISTINCT NULL title, category from table
) t
ORDER BY category, title NULLS FIRST
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top