我现在有一个 table
有字段 Type \UNAME和Point 其中Type 是商品类型,UNAME是用户姓名,Point是每种商品类型的分数,1个用户可以拥有多个类型,每个类型的分数值不一样
记录排列如下
type  uname   poiny
 1     a        2
 2     a        3
 3     a        1 
 1     b        2 
 1     b        3  
 1     b        6
 1     c        5
 1     d        7
 1     e        12
现在要查出  前3名  用户 的 分数做多的人
求SQL 语句

解决方案 »

  1.   

    declare @t table([type] int,uname varchar(10),poiny int) 
    insert @t select 1,    'a',        2 
    insert @t select 2,    'a',        3 
    insert @t select 3,    'a',        1 
    insert @t select 1,    'b',        2 
    insert @t select 1,    'b',        3  
    insert @t select 1,    'b',        6 
    insert @t select 1,    'c',        5 
    insert @t select 1,    'd',        7 
    insert @t select 1,    'e',        12 
    select  top 3 uname,sum(poiny)amount from @t group by uname order  by amount descuname      amount
    ---------- -----------
    e          12
    b          11
    d          7(3 行受影响)
      

  2.   

    不好意思 粗心了  排列结果应该是这样的
    type  uname  poiny 
    1    a        2 
    2    a        3 
    3    a        1 
    1    b        2 
    2    b        3  
    3    b        6 
    1    c        5 
    1    d        7 
    1    e        12 
    每个用户能拥有的商品类型 不能重复
      

  3.   

    取前三名的記錄
    declare @T table([type] int,[uname] nvarchar(1),[poiny] int)
    Insert @T
    select 1,N'a',2 union all
    select 2,N'a',3 union all
    select 3,N'a',1 union all
    select 1,N'b',2 union all
    select 1,N'b',3 union all
    select 1,N'b',6 union all
    select 1,N'c',5 union all
    select 1,N'd',7 union all
    select 1,N'e',12
     
    Select  * from @T  where  [uname] in(select top 3 [uname] from @T group by [uname] order by sum([poiny]) desc) type        uname poiny
    ----------- ----- -----------
    1           b     2
    1           b     3
    1           b     6
    1           d     7
    1           e     12(5 個資料列受到影響)