Declare @ Table
(BillNo varchar(10),
sParent varchar(10)
)Insert Into @
Select 'D001', '' Union
Select 'B001', 'D001' union
Select 'B002', 'D001' union
Select 'X001', 'B001' union
Select 'X002', 'B002' select a.sparent d,a.billno b,b.billno x
from @ a left join @ b
on a.BillNo=b.sParent
where a.sparent='D001'

解决方案 »

  1.   


    --建立测试环境Declare @ table
    (BillNo varchar(10),
    sParent varchar(10)
    )Insert Into @
    Select 'D001', '' Union
    Select 'B001', 'D001' union
    Select 'B002', 'D001' union
    Select 'X001', 'B001' union
    Select 'X002', 'B002' /*
    需要结果
    d b x
    D001 B001 X001
    D001 B002 X002
    */select * from @
     select a.sparent d,a.billno b,b.billno x
    from @ a left join @ b
    on a.BillNo=b.sParent
    where a.sparent='D001'/*
    D001
    B001 X001 D001
    B002 X002 */
      

  2.   

    select a.sparent d,a.billno b,b.billno x
    from @ a left join @ b
    on a.BillNo=b.sParent
    where a.sparent='D001'     --  这条件不能加的,我只是举了个例子,不能具体到某一个单子的!
      

  3.   


    Declare @ Table
    (BillNo varchar(10),
    sParent varchar(10)
    )Insert Into @
    Select 'D001', '' Union
    Select 'B001', 'D001' union
    Select 'B002', 'D001' union
    Select 'X001', 'B001' union
    Select 'X002', 'B002' select * from @
    /*
    需要结果
    d b x
    D001 B001 X001
    D001 B002 X002
    */
    declare @t table (billno varchar(10))
    insert into @t
    select billno from @ where billno like 'd%'
    union all
    select billno from @ where billno like 'b%'
    union all 
    select billno from @ where billno like 'x%'
    select * from @t
    select d=(case when billno like 'd%' then billno else '' end),b=(case when billno like 'b%' then billno else '' end),x=(case when billno like 'x%' then billno else '' end) from @t
    --
    D001
    B001
    B002
    X001
    X002
      

  4.   

    Declare @ Table
    (BillNo varchar(10),
    sParent varchar(10)
    )Insert Into @
    Select 'D001', '' Union
    Select 'B001', 'D001' union
    Select 'B002', 'D001' union
    Select 'X001', 'B001' union
    Select 'X002', 'B002' 
    select y.d,y.b,y.x
    from(select a.sparent d,a.billno b,b.billno x
    from @ a right join @ b
    on a.BillNo=b.sParent)y,@ g
    where g.billno=y.d