select id,(select count(1) from ta where layer > a.layer) as layer from ta a

解决方案 »

  1.   

    declare @t table(ID int,Layer int)
    insert @t 
    select 1,3 union 
    select 2,5 union 
    select 3,6 union 
    select 4,8 union 
    select 5,10 union 
    select 6,1
    select id,(select count(1) from @t where layer > a.layer) as layer from @t a/*id          layer       
    ----------- ----------- 
    1           4
    2           3
    3           2
    4           1
    5           0
    6           5
    */
      

  2.   

    select 
        a1.ID,isnull(count(a2.*),0) as Layer
    from 
        A a1 
    left join 
        A a2
    on
        a1.Layer>a2.Layer
      

  3.   

    select 
        a1.ID,isnull(count(a2.ID),0) as Layer
    from 
        @t a1 
    left join 
        @t a2
    on
        a1.Layer<a2.Layer
    group by
        a1.ID
    order by
        a1.ID