一条Select语句能否写出这样的效果?
需求:
select的结果中的某个字段包含了许多重复的ID,我想只搜出这些重复ID的前10个
比如id:500,数据库中有20个,id:600有30个,我的结果中只希望出现id:500和600各10个。
请问这样的SQL怎么写啊?
用HAVING吗?

解决方案 »

  1.   

    用union all  把它他合到一行中
    select top 100 * from tablename where  id ='500' union all select top 100 * from tablename where  id ='600')变通一下了
      

  2.   

    可是我这个id代表各种分类,至少有8个,难道要写8个union all呀?这个SQL性能就有点问题了吧
      

  3.   

    假设主键是ppselect *
    from table1
    where id in ( select pp from 
    (select a.id,a.pp,count(*)
    from table1 a , table1 b
    where a.id=b.id and a.pp>=b.pp
    group by a.id,a.pp
    having count(*)<=10) e)
    == 思想重于技巧 ==
      

  4.   

    To liuyann:
    我建了一个只有pp主键和id的表,id=100和200各20条记录,
    用你的SQL查询出来是空
      

  5.   

    select *
    from table1
    where pp in ( select pp from 
    (select a.id,a.pp,count(*)
    from table1 a , table1 b
    where a.id=b.id and a.pp>=b.pp
    group by a.id,a.pp
    having count(*)<=10) e)
    == 思想重于技巧 ==
      

  6.   

    select a.id,a.pp,count(*)
    from table1 a , table1 b
    where a.id=b.id and a.pp>=b.pp
    group by a.id,a.pp
    having count(*)<=10
    == 思想重于技巧 ==
      

  7.   

    select a.id,a.pp 
    from table1 a , table1 b
    where a.id=b.id and a.pp>=b.pp
    group by a.id,a.pp
    having count(*)<=10这样就对了,有门儿,不过我那个SQLjoin了3个表,写起来有些复杂。
    多谢啦,去想想怎么写了。
      

  8.   

    好像运算量很大啊,上去MySQL就挂了