如何控制query返回的记录数目?(100分)

  • 主题发起人 主题发起人 侠圣
  • 开始时间 开始时间

侠圣

Unregistered / Unconfirmed
GUEST, unregistred user!
假设一个query返回100条记录(经过排序),如何取出其中部分记录,如1到10,或者30-50
等。后台数据库是oracle。另外下面这条sql语句错在什么地方?
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id order by times desc)
where rownum<11
写成(不加排序)
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id)
where rownum<11
就对了
我得目的是要实现返回排序后记录中的第m名到第n名
 
oracle好象不能支持从m到n的方法(或者我不知道),不过,你可以
通过检索前n,前m条记录,之后在相减.
通过union test
 
建一汇总TABLE。查询前先汇总。
 
rownum如果是连续唯一的,可以rownum>n and rownum<m
如果不是,只有先把结果放到本地的临时表里了,一个一个取记录
 
用视图吧,较好的解决办法了
create view temp as select pgm_id,count(*) as times from vod_rec group by pgm_id order by times desc
select * from temp where rownum<11
drop view temp
 
假如m=3,n=10。

Select top 10-3 *
from(
select top 10 * from (select pgm_id,count(*) as times from vod_rec group by pgm_id order by times desc)
where rownum<11
order by times desc
)
order by times

大体如此,
我还没试过,理论上可行,你就安这个思路我试试,
如有疑问再联系。


 
我前两天刚问过这问题
http://www.delphibbs.com/delphibbs/DispQ.asp?LID=359330
 
SQL Server 可以加入范围子句:
Select Top 10 * From ...
 
11-20
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id)
where rownum<21
union all
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id)
where rownum<11


 
不好意思,错了
11-20
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id)
where rownum<21
minus
select * from (select pgm_id,count(*) as times from vod_rec group by pgm_id)
where rownum<11

 
后一问题的错误在于Order by后的字段是找不到的,您可以直接用Count(*)来代替.
 
多人接受答案了。
 
后退
顶部