create table #article(id int ,modelId int ,modelNo varchar(50), title varchar(200) )
declare @modelId   int DECLARE  Cur1 cursor for
    SELECT   id, modelNo    FROM  pageModel    
   OPEN  Cur1
   FETCH next from Cur1 INTO @modelId     WHILE  @@fetch_status<>-1 
   BEGIN 
     Insert Into #article
       Select a.id,a.modelId ,b.modelNo,a.title     
          From  article  a,pageModel  b   
          Where a.modelId=b.id and
                a.id in(select top 5 id from article where modelId= @modelId )
     FETCH next from  Cur1 INTO @modelId  
   END  
   CLOSE  Cur1
   DEALLOCATE  Cur1Select * from #article
Order by   modelId,id 
Drop table  #article

解决方案 »

  1.   

    --假设以ID从小到大排序
    --将数据放入一个临时表.
    elect a.modelNo , b.id, b.title into temp from article a, pageModel b where a.modelId = b.id
    --获取每类的前五条记录.
    select * from temp as t
    where (select count(*) from temp where modelNo = t.modelNo and id < t.id) < 5
      

  2.   

    在sql server 2005中,用cte或rank over都可以实现.
      

  3.   

    大家注意,ID雖然是自動遞增生成,但有些記錄段可能會被刪除,所以直接用 < 5這是不行的,必須用TOP 5來取得最上5個ID,再select top 5 ...not in (select TOP 5 ID...) order by ID才能得到准確的結果
      

  4.   

    在项目里遇到一个难题,有两张表如下:
    文章表   article      字段 id, modelId(对应 pageModel 中的 id), title
    版块表   pageModel    字段 id, modelNo--OK ,
    select * from article a where a.id in (select top 5 id from article   where pageModel = a.pageModel )