现有一视频表 有三个字段 id :    视频ID ,唯一标识列  
count:  视频被点击 次数
type:    视频的类别(比如a类,b类,c类,d,e,f,g.........等)因为首页要放视频点击次数最高的2个类别,并且每个类别取点击数最高的2个(比较的不是每种类别视频下的所有视频的点击次数的总和,而是比的单个视频的点击次数),不知道我这样表述是否各位大哥大姐能明白。
现在的数据是这样:id        count            type
1         50               a
2         51               a
3         52               a   
4         53               a5         60               b
6         61               b
7         62               b
8         63               b9         30               c
10        31               c
11        32               c 12        80               d
13        81               d
14        82               d         那么我想要的统计结果应该是id        count            type
7         62               b
8         63               b  
13        81               d
14        82               d       
麻烦各位了!!!!!!!!!

解决方案 »

  1.   

    --建立测试
    if object_id('tb') is not null drop table tb
    go
    create table tb(id int identity,cnt int,type varchar(1))
    insert tb
    select 50               ,'a' union all
    select 51               ,'a' union all
    select 52               ,'a' union all
    select 53               ,'a' union allselect 60               ,'b' union all
    select 61               ,'b' union all
    select 62               ,'b' union all
    select 63               ,'b' union allselect 30               ,'c' union all
    select 31               ,'c' union all
    select 32               ,'c' union allselect 80               ,'d' union all
    select 81               ,'d' union all
    select 82               ,'d'         
    go
    select * 
    from tb t
    where id in 
        (select top 2 id 
        from tb 
        where type=t.type and type in 
         (select top 2 type from tb group by type order by sum(cnt)desc)
        order by cnt desc
        )
    --结果
    /*(所影响的行数为 14 行)id          cnt         type 
    ----------- ----------- ---- 
    7           62          b
    8           63          b
    13          81          d
    14          82          d(所影响的行数为 4 行)*/
      

  2.   

    谢谢 xys_777!!!!  问题解决!!!