今天找资料,看到一条语句:
目的:把每个用户的前100条记录提取出来
语句:
select t.* from A t where iDataId in(select top 100 iDataId from A where iPersonId=t.iPersonId order by dUseTime)效果达到了,但不知道所以然,请各位兄弟帮忙理解一下;引用地址:
http://topic.csdn.net/u/20090217/16/d2e90f06-7f90-4e16-afe4-7458f5947efe.html

解决方案 »

  1.   

    按dUseTime排序,取每个人前100条iDataId。
      

  2.   

    --子查询为前一百条记录
    where iDataId in(select top 100 iDataId from A where iPersonId=t.iPersonId order by dUseTime
      

  3.   


    select t.* 
    from A t 
    where iDataId in(
                    select top 100 iDataId 
                    from A 
                    where iPersonId=t.iPersonId 
                    order by dUseTime) 
    ---iDataId 必须为唯一值,如果不唯一的话将达不到效果
    /*
    select top 100 iDataId 
                    from A 
                    where iPersonId=t.iPersonId  --把t.iPersonId 改为你想要的字符串 你就能理解了!
                    order by dUseTime
    */
      

  4.   


    这个我知道,我想请问,为什么一个表这样联合查询就能得到条个用户的前N条,而不用group by之类的
      

  5.   

    前面各位兄弟回答都正确,但是好象还差更深层的意思
    比如说:为什么内层的select top 100 iDataId 
                    from A 
                    where iPersonId=t.iPersonId 
                    order by dUseTime这个TOP 100 一定能确定那个iDataId人集合是每个用户100条呢?
      

  6.   

    因为有iPersonId=t.iPersonId这个限制
      

  7.   

    嵌套循环类似for(i=1;i<10;i++)
    {
      for (y=1;y<10;y+)
       ...........
    }
    --iDataId 必须为唯一值,如果不唯一的话将达不到效果????/既是相同也没关系啊 where iDataId in (1,1) 和where iDataId in (1) 有什么区别吗? 
      

  8.   

    1.select a.* from tb a where 1 > (select count(*) from tb where name = a.name and val > a.val ) order by a.name2.select a.* from tb a where not exists(select 1 from tb where name = a.name and val > a.val)3.select a.* from tb a where exists (select count(*) from tb where name = a.name and val < a.val having Count(*) < 2) order by a.name,a.val
    /*--按name分组取最小的两个(N个)val
    多看看这样的写法就能明白了
      

  9.   

    这里理解下SELECT 查询原理,这个语句分2层查询,外层和内层。它执行的时候先读取一条外层的记录,通过这个条记录获得iDataId, iPersonId ;然后再判断内层查询,即这个iDataId是不是在iPersonId的值为外层记录的iPersonId 前100条记录。
      

  10.   

      除了这样达到效果,还可以怎么写? 要求一条SQL解决