不用group by
select * 
from tbl aa
where    id=(select min(id) from tbl where class=aa.class)
      or id=(select max(id) from tbl where class=aa.class)

解决方案 »

  1.   

    select * from #t where id in
    (select max(id) from #t group by class union select min(id) from #t group by class)
    order by class
      

  2.   

    select * from 表 
    where id in(
          select max(id) from 表 group by class
          union all
          select min(id) from 表 group by class
          )
      

  3.   

    --这样,用group by而且效率会更好一点
    select a.* 
    from 表 a join 表 b
    on a.class = b.class
    group by a.id,a.name,a.class
    having (count(case when a.id >= b.id then 1 end) = 1) or (count(case when a.id >= b.id then 1 end) = count(*))
      

  4.   

    --测试
    declare @ table(id int identity,class int)insert @
    select 1
    union all
    select 1
    union all
    select 1
    union all
    select 2
    union all
    select 2
    union all
    select 2
    union all
    select 3
    union all
    select 3
    union all
    select 3select a.* from @ a join @ b
    on a.class = b.class
    group by a.id,a.class
    having (count(case when a.id >= b.id then 1 end) = 1) or (count(case when a.id >= b.id then 1 end) = count(*))/*
    id          class       
    ----------- ----------- 
    1           1
    3           1
    4           2
    6           2
    7           3
    9           3(所影响的行数为 6 行)
    */
      

  5.   

    select * from test where id in
    (select min(id) from test group by class)
    union all
    select * from test where id in
    (select max(id) from test group by class)
    order by class asc
    -------------------------
    1 xz 1
    3 xl 1
    4 lz 2
    6 lw 2
    9 dw 3
    7 dz 3
      

  6.   

    shuiniu(飞扬的梦)(我是一头只吃西红柿的水牛)   的方法好
      

  7.   

    to:shuiniu(飞扬的梦)(我是一头只吃西红柿的水牛) 
    我需要在结果中显示出Name
    还要用group by
      

  8.   

    --这个不是有name字段嘛?
    select a.* 
    from 表 a join 表 b
    on a.class = b.class
    group by a.id,a.name,a.class
    having (count(case when a.id >= b.id then 1 end) = 1) or (count(case when a.id >= b.id then 1 end) = count(*))