如何实现这样的查询
ID	名称	父项 
 1	类一	0	 
 2	类二	0 
 3	项一	1 
 4	项二	1 
 5	项三	2 
 6	项四	2 
 7	类三	0 
 8	项五	7 
 9	项6		1   
 如何通过SQL查询形成如下格式 
 1	类一	0	 
 3	项一	1 
 4	项二	1 
 9	项六	1 
 2	类二	0 
 5	项三	2 
 6	项四	2 
 7	类三	0 
 8	项五	7 
------解决方案--------------------只有两层可以 
 select a.* from tablename a left join tablename b 
 on a.父项=b.ID 
 order by isnull(b.id,a.id),a.id 
------解决方案--------------------create table #([ID] int,[name] nvarchar(10),pID int) 
 insert into # 
 select 1, '类一 ',0 union all 
 select 2, '类二 ',0 union all 
 select 3, '项一 ',1 union all 
 select 4, '项二 ',1 union all 
 select 5, '项三 ',2 union all 
 select 6, '项四 ',2 union all 
 select 7, '类三 ',0 union all 
 select 8, '项五 ',7 union all 
 select 9, '项六 ',1     
 select A.* from # A left join # B on a.pID = b.[ID] 
 order by isnull(B.[ID],A.[ID]),A.[ID] 
------解决方案--------------------if object_id( 'temp ')> 0 drop table temp 
 create table temp(ID int,[名称] varchar(20),[父项] int)    
 insert into temp 
 select 1, '类一 ',0	 
 union all  
 select 2, '类二 ',0 
 union all  
 select 3, '项一 ',1 
 union all  
 select 4, '项二 ',1 
 union all  
 select 5, '项三 ',2 
 union all  
 select 6, '项四 ',2 
 union all  
 select 7, '类三 ',0 
 union all  
 select 8, '项五 ',7 
 union all  
 select 9, '项六 ',1     
 select *  from  temp 
 order by case when [父项]=0 then ID else [父项] end,id     
 /* 
 1	类一	0	 
 3	项一	1 
 4	项二	1 
 9	项六	1 
 2	类二	0 
 5	项三	2 
 6	项四	2 
 7	类三	0 
 8	项五	7 
 */    
 drop table temp