现有一视频表三个字段 
id : 视频ID ,唯一标识列    
count:  视频被点击 次数
type: 视频的类别(比如a类,b类,c类,d,e,f,g.........等)现在想统计出  每种类别中点击次数最高的3个视频  统计的结果如下id     count         type
1      100            a类
2      101            a类
3      200            a类 
5      89             b类
6      91             b类
18     108            b类意思就是每种取点击次数最高的三个
请问高手们怎么用一条SQL语句统计?

解决方案 »

  1.   

    select *
    from tn k
    where id in (select top 3 id from tn where [type]=k.type order by [count] desc )
      

  2.   

    --sql 2005select p.*
    from tn k cross apply (select top 3 * from tn where k.type=type order by [count] desc) p
      

  3.   

    feixianxxx这位兄弟 我试了你的语句  都不对,,,,,,,,
    以下是我的原始数据1 100 a
    2 99 a
    3 101 a
    4 102 a
    5 100 b
    6 103 b
    7 102 b
    8 101 b
    根据你的第一条语句 统计结果如下1 100 a
    2 99 a
    3 101 a
    5 100 b
    6 103 b
    7 102 b第二条的结果如下4 102 a
    3 101 a
    1 100 a
    4 102 a
    3 101 a
    1 100 a
    4 102 a
    3 101 a
    1 100 a
    4 102 a
    3 101 a
    1 100 a
    6 103 b
    7 102 b
    8 101 b
    6 103 b
    7 102 b
    8 101 b
    6 103 b
    7 102 b
    8 101 b
    6 103 b
    7 102 b
    8 101 b
      

  4.   

    select *
    from tn k
    where id in (select top 3 id from tn where [type]=k.type order by [count] desc )
    如果ID是唯 一,应该没问题吧
      

  5.   

    ------------------------------------
    -- Author: flystone  
    -- Version:V1.001  
    -- Date:2010-06-18 
    -------------------------------------- Test Data: ta
    If object_id('ta') is not null 
        Drop table ta
    Go
    Create table ta(id int,count int,type nvarchar(2))
    Go
    Insert into ta
    select 1,100,'a类' union all
    select 2,101,'a类' union all
    select 3,200,'a类' union all
    select 4,102,'a类' union all
    select 5,100,'b类' union all
    select 6,103,'b类' union all
    select 7,102,'b类' union all
    select 8,101,'b类' 
    Go
    --Start
    select a.*
    from ta a join ta b 
    on a.type = b.type
    group by a.id,a.count,a.type
    having count(case when a.count <= b.count then 1 else null end)<= 3
    order by a.type,a.count desc--Result:
    /*
    id          count       type 
    ----------- ----------- ---- 
    3           200         a类
    4           102         a类
    2           101         a类
    6           103         b类
    7           102         b类
    8           101         b类(所影响的行数为 6 行)*/
    --End