有一表
表名tb
編號  分類ID  數值
1      1      30
2      1      10
3      1      30
4      1      40
5      2      88
5      2      20
5      2      13
5      2      72
5      2      72要求﹕取得每組(分類ID相同)中數值最大的前兩個記錄。

解决方案 »

  1.   

    表名tb
    編號  分類ID  數值
    1      1      30
    2      1      10
    3      1      30
    4      1      40
    5      2      88
    6      2      20
    7      2      13
    8      2      72
    9      2      72得到如下結果﹕
    編號  分類ID  數值
    4       1      40
    1       1      30
    5      2      88
    8      2      72
      

  2.   

    declare @tmp table(編號 int, 分類ID int, 數值 int)
    insert into @tmp select 1  ,    1   ,   30
    union select 2  ,    1   ,   10
    union select 3  ,    1   ,   30
    union select 4  ,    1   ,   40
    union select 5  ,    2   ,   88
    union select 6  ,    2   ,   20
    union select 7  ,    2   ,   13
    union select 8  ,    2   ,   72
    union select 9  ,    2   ,   72SELECT * FROM @tmp A
    WHERE 編號 IN
    (SELECT TOP 2 編號 FROM @tmp WHERE a.分類ID=分類ID   ORDER BY 數值 DESC)
      

  3.   

    drop table #a
    create table #a(编号 varchar(20),id1 int,数值 int)
    insert into #a
    select '1',1,30 union all
    select '2',1,10 union all
    select '3',1,30 union all
    select '4',1,40 union all
    select '5',2,88 union all
    select '6',2,20 union all
    select '7',2,13 union all
    select '8',2,72 union all
    select '9',2,72SELECT * FROM #a A
    WHERE 编号 IN
    (SELECT TOP 2 编号 FROM #a WHERE a.ID1=ID1   ORDER BY 数值 DESC)
      

  4.   

    declare @tb table(id int,classId int ,num int)
    insert @tb
    select 1,1,30 union all
    select 2,1,10 union all
    select 3,1,30 union all
    select 4,1,40 union all
    select 5,2,88 union all
    select 6,2,20 union all
    select 7,2,13 union all
    select 8,2,72 union all
    select 9,2,72 select * from @tb a where [id] in (select top 2 [id] from @tb b where a.[classid]=b.[classid] order by num desc) order by classid,num desc 4 1 40
    3 1 30
    5 2 88
    8 2 72