我有一个表
ID ClassName ParentID
1     a         0
2     b         0
3     aa        1
4     aaa       3
5     aaaa      4
6     bb        2
7     bbb       6要求数据独出来的是这样的
a
aa
aaa
aaaa
b
bb
bbb
不知道我写的你能明白不,新手求高手帮助

解决方案 »

  1.   

    select ClassName  from tb order by ClassName 
      

  2.   


    select ClassName  from tb order by ClassName , ParentID
      

  3.   


    with cte as
    (
    select *,p=t.id from t where pid=0
    union all
    select a.*,p=b.p*10+a.id from t a join cte b on a.pid=b.id
    )
    select * from cte order by cast(p as varchar(10))/*
    id          c          pid         p
    ----------- ---------- ----------- -----------
    1           a          0           1
    3           aa         1           13
    4           aaa        3           134
    5           aaaa       4           1345
    2           b          0           2
    6           bb         2           26
    7           bbb        6           267
    */
      

  4.   

    --建表
    create table #Class(ID int, Classname varchar(10), ParentID int)
    --写数据
    insert into #Class
    select 1,'a',0 union all
    select 2,'b',0 union all
    select 3,'aa',1 union all
    select 4,'aaa',3 union all
    select 5,'aaaa',4 union all
    select 6,'bb',2 union all
    select 7,'bbb',6 union all--显示select Classname from #Class order by left(classname,1)+cast(ParentID as varchar)
    --结果
    Classname
    ----------
    a
    aa
    aaa
    aaaa
    b
    bb
    bbb(7 行受影响)