mssql server中如下,只是多了一行 '没用':select top 2  id, name, type, count(type) '没用'
from a group by id, name, type行不行?????????

解决方案 »

  1.   

    找出各类型中排第三名的记录的ID号,ID号小于此号的就是前2条。
    select * 
    from a t4,
      (select t1.type,t1.id 
      from a t1,a t2
      where t1.type=t2.type and t1.id>t2.id
      group by t1.type,t1.id
      having count(t2.ID)=2) t3
    where t4.type=t3.type and t4.id<t3.id
      

  2.   

    Sorry,如果不想在程序中出现TempTable,只有用 Proc(实际上在Proc中也会出现TempTable,嘿嘿),我建议在程序中利用数据集的优势,配合TempTable,最有效率,以后也方便维护,免得两头忙。如有兴趣,我给你写一个Demo.
      

  3.   

    这是每种类型取最新一条记录sql语句:
    select * from a where id in (select max(id) from a group by type )
    这是取第二新的语句:
    select * from a 
           where id in ( select max(id)
                         from a ,(select max(id) as maxid,type from a group by type ) b  
                         where a.type = b.type and a.id < b.maxid 
                         group by a.type ) 
           
    让后将两部分union起来。
    我觉得就取一条挺好的,效率比较高,取两条效率不高
      

  4.   

    icevi(按钮工厂) 的应该是
    select t4.* 
    from a t4,
      (select t1.type,t1.id 
      from a t1,a t2
      where t1.type=t2.type and t1.id>t2.id
      group by t1.type,t1.id
      having count(t2.ID)=2) t3
    where t4.type=t3.type and t4.id<t3.id我感觉icevi(按钮工厂) 的方法比我的好,但不知道好多少,大家说说。
      

  5.   

    pxq(风轻轻地吹) :
    是应该改成select t4.* ,老兄眼好尖啊,哈哈