문제

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

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top