Oracle 根據行列號取值

來源:互聯網
上載者:User

//資料  
 A   B  C  
--  -- --  
a1  b1 c1  
a2  b2 c2  
a3  b3 c3  
//結果:  
row  col  value  
--   ---  -----  
 1     1  a1  
 1     2  b1  
 1     3  c1  
 2     1  a2  
 2     2  b2  
 2     3  c2  
 3     1  a3  
 3     2  b3  
 3     3  c3  
--  
with tb as(  
     select 'a1' a,'b1' b,'c1' c from dual union all  
     select 'a2','b2','c2' from dual union all  
     select 'a3','b3','c3' from dual)  
select rn,1,a from (select a,b,c,rownum as rn from tb )  
union   
select rn,2,b from (select a,b,c,rownum as rn from tb )  
union   
select rn,3,c from (select a,b,c,rownum as rn from tb )  
--  
//解析:  
//通過執行子查詢,從結果中我們看到了,對於每一行都返回了一個rn(每行行號);  
//對於每一個行號,執行上面的select union查詢,每一次union,都返回一個結果集;  
//串連指定的1,2,3,和每一個rn對應的a,b,c值,就得到了我們想要的結果。  
//例如rn=1時:  
 1     1  a1  
 1     2  b1  
 1     3  c1  
--  
SQL> with tb as(  
  2       select 'a1' a,'b1' b,'c1' c from dual union all  
  3       select 'a2','b2','c2' from dual union all  
  4       select 'a3','b3','c3' from dual)  
  5       select a,b,c,rownum as rn from tb  
  6  /  
A  B  C          RN  
-- -- -- ----------  
a1 b1 c1          1  
a2 b2 c2          2  
a3 b3 c3          3 

相關文章

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.