有一个表数据结构如下
Model   Qty
A       50
A       30
A       20
A       10
B       20
B       15
C       5
C       10
C       12
C       16
我想要得到的结果是取各个model的qty前2大的纪录如下?
A       50
A       30
B       20
B       15
C       16
C       12

解决方案 »

  1.   

    create table test(Model varchar(10),Qty int)
    insert test select 'A',50
    union all select 'A',30
    union all select 'A',20
    union all select 'A',10
    union all select 'B',20
    union all select 'B',15
    union all select 'C',5
    union all select 'C',10
    union all select 'C',12
    union all select 'C',16select * from test a where Qty in 
    (
    select top 2 Qty from test where Model=a.Model order by Qty desc
    )
      

  2.   

    create table ta (Model nvarchar(10),   Qty int )
    insert into ta 
    select 'A',       50
    union select 'A',       30
    union select 'A',       20
    union select 'A',       10
    union select 'B',       20
    union select 'B',       15
    union select 'C',       5
    union select 'C',       10
    union select 'C',       12
    union select 'C',       16select  Model,Qty
    from ta a 
    where (select count(*) from ta  b where a.Model=b.Model and a.Qty<b.Qty ) <2--result
    A 30
    A 50
    B 15
    B 20
    C 12
    C 16
      

  3.   

    Model      Qty         
    ---------- ----------- 
    A          50
    A          30
    B          20
    B          15
    C          12
    C          16(所影响的行数为 6 行)
      

  4.   

    create table ta (Model nvarchar(10),   Qty int )
    insert into ta 
    select 'A',       50
    union select 'A',       30
    union select 'A',       20
    union select 'A',       10
    union select 'B',       20
    union select 'B',       15
    union select 'C',       5
    union select 'C',       10
    union select 'C',       12
    union select 'C',       16select  Model,Qty
    from ta a 
    where (select count(*) from ta  b where a.Model=b.Model and a.Qty<b.Qty ) <2--result 
    A 30
    A 50
    B 15
    B 20
    C 12
    C 16
      

  5.   

    if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb(Model varchar(10),Qty int)
    insert into tb(Model,Qty) values('A',       50)
    insert into tb(Model,Qty) values('A',       30)
    insert into tb(Model,Qty) values('A',       20)
    insert into tb(Model,Qty) values('A',       10)
    insert into tb(Model,Qty) values('B',       20)
    insert into tb(Model,Qty) values('B',       15)
    insert into tb(Model,Qty) values('C',       5)
    insert into tb(Model,Qty) values('C',       10)
    insert into tb(Model,Qty) values('C',       12)
    insert into tb(Model,Qty) values('C',       16)
    goselect * from tb as t
    where (select count(*) from tb where Model = t.Model and Qty > t.Qty) < 2drop table tb/*
    Model      Qty         
    ---------- ----------- 
    A          50
    A          30
    B          20
    B          15
    C          12
    C          16(所影响的行数为 6 行)
    */