Oracle 返回偶數個資料行

來源:互聯網
上載者:User

要求:

查詢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

返回結果:

說明:如果資料行數為偶數時,直接返回資料行的所有資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.