表t_c 和t_p如上图
select * from t_c
select * from t_p
查询方法一:
select * from (select row_number() over(partition by cid order by cdate desc) as rowid,* from t_p) T where T.rowid<=5
使用sql2005的特性 row_number() over()
方法二:
declare @temp table(id int,cid int,cdate datetime);
declare @id int;
declare cur cursor for
select cid from t_c
open cur
fetch next from cur Into @id
while @@fetch_status = 0
begin
insert into @temp
select top 5 * from t_p where cid = @id order by cdate desc
fetch next from cur into @id
end
close cur
deallocate cur
select * from @temp
利用游标和表变量