|
本帖最后由 2544370078 于 2012-7-11 16:11 编辑
要求:
查询Oracle表中的数据个数为奇数个时,自动加一个空白行,返回偶数个数据;如果表中的数据为偶数个时,直接返回偶数的所有行。
一、在数据库中,新建一个表,如下:
1.create table MONTHSNUM
2.(
3. MONTHS NUMBER
4.)
create table MONTHSNUM
(
MONTHS NUMBER
)二、新增一行数据;
1.insert into monthsnum values(1);
insert into monthsnum values(1);三、执行SQL:
1.select *
2. from (select aa.*, mod(bb.countnum, 2) num
3. from (select a.*, rownum rownum2
4. from (select rownum rownum1, t.months
5. from monthsnum t
6. union
7. select to_number('') rownum1, to_number('') months
8. from dual) a) aa,
9. (select count(*) + 1 countnum from monthsnum t) bb
10. order by aa.rownum2)
11.where rownum <= (case when num = 0 then rownum else
12. (select count(*) countnum from monthsnum t) end) select *
from (select aa.*, mod(bb.countnum, 2) num
from (select a.*, rownum rownum2
from (select rownum rownum1, t.months
from monthsnum t
union
select to_number('') rownum1, to_number('') months
from dual) a) aa,
(select count(*) + 1 countnum from monthsnum t) bb
order by aa.rownum2)
where rownum <= (case when num = 0 then rownum else
(select count(*) countnum from monthsnum t) end) 返回结果:
说明:如果数据行数为奇数时,补一个空白行,使其为行数为偶数。
四、再新增一行数据;
1.insert into monthsnum values(2);
insert into monthsnum values(2);五、再执行第三步的SQL
返回结果:
说明:如果数据行数为偶数时,直接返回数据行的所有数据。
|
|