日期:2014-05-17 浏览次数:20806 次
--1. 构建测试表test id 范围为 0 -- 178 SQL> create table test (id) as select trunc(dbms_random.value(0,179)) from dual connect by level < 10000 ; Table created. --2. 构建范围表range_ SQL> create table range_ ( begin_ number , end_ number , id number) ; Table created. SQL> insert into range_ values (0,27,1) ; 1 row created. SQL> insert into range_ values (27,48,2) ; 1 row created. SQL> insert into range_ values (48,96,3) ; 1 row created. SQL> insert into range_ values (96,111,4) ; 1 row created. SQL> insert into range_ values (111,178,5) ; 1 row created. SQL> commit ; Commit complete. SQL> select * from range_ order by id ; BEGIN_ END_ ID ---------- ---------- ---------- 0 27 1 27 48 2 48 96 3 96 111 4 111 178 5 --目标 根据 范围表 range_ 的列 begin_ end_ 统计 test 表中的数据分布情况 --目标结果集举例: BEGIN_ END_ ID COUNT ---------- ---------- ---------- ------- 0 27 1 2000 27 48 2 1999 48 96 3 2001 96 111 4 1888 111 178 5 2111
select r.*, (select count(*) from test t where (t.id > r.begin_ and t.id <= r.end_) --不是从0开始的计数 or (t.id >= r.begin_ and t.id <= r.end_ and r.begin_=0)--从0开始的计数 ) as count from range_ r;