有一个表AAA,结构如下:
类别编号   说明     排序
  a          aa      1
  a          aa2     2
  a          aa3     3
  b          bb      1
  b          bb2     2
  b          bb3     3
  c          cc      1
  c          cc2     2
  c          cc3     3
需要查询出来的结果是每个类别的头2条记录,按排序进行排序,结果如下:
类别编号   说明     排序
  a          aa      1
  a          aa2     2
  b          bb      1
  b          bb2     2
  c          cc      1
  c          cc2     2
谢谢各位了!只要测试通过马上给分!

解决方案 »

  1.   

    如何取每个种类的前百分之x的记录示例数据(表a):  
    area cust money  
    --------------  
    A    123  20.0  
    A    159  20.0  
    A    456  25.0  
    A    483  30.0  
    A    789  40.0  
    A    597  50.0  
    B    147  10.0  
    B    258  20.0  
    B    369  25.0  
    B    384  30.0   
     
    希望得到的如下结果  
    area cust money  
    --------------  
    A    483  30.0  
    A    789  40.0  
    A    597  50.0  
    B    369  25.0  
    B    384  30.0  
     
    现有表a,想得到表a中各地区(area)的商户(cust)交易金额(money)排该地区里面前百分之50%的记录.  
    即要:  
    地区A中金额前百分之50%  
    地区B中金额前百分之50%  
    ....C..............50%  
    ....D..............50%
    ......................  CREATE TABLE #a (
           [area] [char] (10),
           [cust] [char] (10),
           [money] [numeric](10, 1) NULL 
    )insert into #a(area,cust,money) values('A','123',20.0)  
    insert into #a(area,cust,money) values('A','159',20.0)  
    insert into #a(area,cust,money) values('A','456',25.0)  
    insert into #a(area,cust,money) values('A','483',30.0)  
    insert into #a(area,cust,money) values('A','789',40.0)  
    insert into #a(area,cust,money) values('A','597',50.0)  
    insert into #a(area,cust,money) values('B','147',10.0)  
    insert into #a(area,cust,money) values('B','258',20.0)  
    insert into #a(area,cust,money) values('B','369',25.0)  
    insert into #a(area,cust,money) values('B','384',30.0)   select * from #a t
    where cust in 
    (
    select top 50 percent cust from #a where area=t.area order by money desc
    )drop table #a//结果
    area       cust       money        
    ---------- ---------- ------------ 
    A          483        30.0
    A          789        40.0
    A          597        50.0
    B          369        25.0
    B          384        30.0(所影响的行数为 5 行)
      

  2.   

    select 
        t.* 
    from 
        表 t 
    where 
        t.说明 in(select top 2 说明 from 表 where 类别编号=t.类别编号 order by 说明)
      

  3.   

    将上面的top 50 percent 换成 top 2
      

  4.   

    select * from aaa a
    where 排序 in (
    select top 2 排序 from aaa where 类别编号=a.类别编号 order by 排序
    )
      

  5.   

    select * from AAA as t
    where (select count(*) from AAA where 类别编号 = t.类别编号 and 排序 < t.排序) < 2
    --或
    select * from AAA as t
    where not exists(select 1 from AAA where 类别编号 = t.类别编号 and 排序 < t.排序 group by 类别编号 having count(*) > 1)