我有张表:user 列:id,charm,name  其中charm 是int型,存储魅力值的,现在假如id= 123的用户的charm值= 432 ,求id=123的用户根据charm排序后,该用户是排行第几?这个在数据中怎么弄啊

解决方案 »

  1.   

    select *,
           排名=(select count(*) from [user] where charm>t.charm)
    from [user] t
      

  2.   

    select * from (
    select *,(select count(*) from tb b where a.charm<=b.charm) as rn
    from tb a) a
    where a.id=123
      

  3.   

    select * from (
    select *,(select count(distinct b.charm) from tb b where a.charm<=b.charm) as rn
    from tb a) a
    where a.id=123可以求并列的
      

  4.   

    --2005直接用排名函数
    select
      *,
      排名=row_number()over(partition by id order by charm),*
    from
      tb
    where
      id=123
      

  5.   

    --> 测试数据:[TB]
    if object_id('[TB]') is not null drop table [TB]
    create table [TB]([id] int,[point] int,[name] varchar(4))
    insert [TB]
    select 1,100,'张三' union all
    select 2,80,'李四' union all
    select 3,80,'王五' union all
    select 4,75,'杨六' union all
    select 5,75,'方七'select id=(select count([point])+1 from TB where T.[point]<[point]),point,name
    from TB t/*
    id          point       name
    ----------- ----------- ----
    1           100         张三
    2           80          李四
    2           80          王五
    4           75          杨六
    4           75          方七(5 行受影响)
    */drop table TB--> 测试数据:[TB]
    if object_id('[TB]') is not null drop table [TB]
    create table [TB]([id] int,[point] int,[name] Nvarchar(4))
    insert [TB]
    select 1,100,N'张三' union all
    select 2,80,N'李四' union all
    select 3,80,N'王五' union all
    select 4,75,N'杨六' union all
    select 5,75,N'方七'select id=(select count(distinct point) from TB where T.[point]<=[point]),
           point,
           [name]
    from TB t
    /*
    id          point       name
    ----------- ----------- ----
    1           100         张三
    2           80          李四
    2           80          王五
    3           75          杨六
    3           75          方七(5 個資料列受到影響)
    */