一个表
id int, cid int
有100万条记录,求一个sql语句可以对每个cid取id最大的3条记录。如:
id     cid
------
10      1
9       1
8       1
27      2
26      2
25      2
....

解决方案 »

  1.   

    select * from tb a where 3>(select count(1) from tb b where b.cid=a.cid and b.cid>a.cid)或者select * from tb a where id in(select top 3 id from tb b where b.cid=a.cid order by id desc)
      

  2.   

    select a.* from 表 a 
    where id in (select top 3 id from 表 where cid=a.cid order by id desc)
      

  3.   

    select *
    from table1 a
    where id in (select top 3 id from table1 where cid=a.cid order by id desc)
      

  4.   

    select * from tb a where exests(select top 3 id from tb b where b.cid=a.cid order by id desc)
    用ESISTS 要比IN的效率要高,查询速度快
      

  5.   

    select * from tb a where id in(select top 3 id from tb where exists
    (select 1 from tb group by cid having count(cid)>=3  ) order by id desc)
      

  6.   


    select * from yourTable A
    where (select count(1) from yourTable where cid=A.cid and id>A.id)<3
      

  7.   

    to:zhangyanxxxx(张言) 
    你的句子确定能得到LZ想要的结果?
      

  8.   

    各位兄弟,大家的方法我都一一用查询分析器跑过一遍,最快的预计成本也超过了10000。这个表的数据量太大了。
    id为pk,cid建立了索引,但并非聚集索引,有没有哪位高手可以给出一个快捷的解决方案?
      

  9.   

    select * from tb a where 3>(select count(1) from tb b where b.cid=a.cid and b.id>a.id)
    这差不多已经是最快的写法了.
    给cid,id加上索引看看.
      

  10.   

    想了半天,觉得还是对cid分页,然后用
    select top id, cid from a where cid = 1
    uinon all
    select top id, cid from a where cid = 2
    union all
    ...
    的查询比较迅速。
      

  11.   

    如果这样,你知道有多少个cid,它们都是什么吗?枚举可能吗?
      

  12.   

    to:talkinsmile(笑侃)
    select top id, cid from a where cid = 1
    uinon all
    select top id, cid from a where cid = 2
    union all
    ...这样是迅速了...CID如果有几千种可能你怎么写?
      

  13.   

    这样会迅速?每个union的select从表中取数据时是遍历表的知道吗?再将多个select合集时又要进行各样的操作,没有必要最好别用它.
      

  14.   

    就算你用游标,动态生成这个SQL语句,可varchar变量最大8000,@SQL怎么生成呢?
      

  15.   

    to:fcuandy(www.idotnet.org)
    这个CID字段肯定有索引吧...应该不用遍历表的,索引查询就行了。