【SQL】行列轉換方法示例

secooler發表於2010-09-27
一、
1.建立測試表test,並初始化實驗資料
sec@ora10g> create table test (name_id varchar2(10), name varchar2(10));
sec@ora10g> insert into test values ('01','Andy1');
sec@ora10g> insert into test values ('01','Andy2');
sec@ora10g> insert into test values ('01','Andy3');
sec@ora10g> insert into test values ('01','Andy4');
sec@ora10g> insert into test values ('02','Steven1');
sec@ora10g> insert into test values ('02','Steven2');
sec@ora10g> insert into test values ('02','Steven3');
sec@ora10g> insert into test values ('02','Steven4');
sec@ora10g> commit;

2.檢視測試表資料
sec@ora10g> select * from test order by name_id;

NAME_ID    NAME
---------- ----------------------------------------
01         Andy1
01         Andy4
01         Andy3
01         Andy2
02         Steven1
02         Steven4
02         Steven3
02         Steven2

8 rows selected.

3.我們按照name_id不同值將該表橫向轉換如下
SELECT     t1.name_id,
           SUBSTR (MAX (SYS_CONNECT_BY_PATH (t1.NAME, ';')), 2) NAME
      FROM (SELECT a.name_id, a.NAME,
                   ROW_NUMBER () OVER (PARTITION BY a.name_id ORDER BY a.NAME) rn
              FROM TEST a) t1
START WITH t1.rn = 1
CONNECT BY t1.name_id = PRIOR t1.name_id AND t1.rn - 1 = PRIOR t1.rn
  GROUP BY t1.name_id;


NAME_ID    NAME
---------- ----------------------------------------
01         Andy1;Andy2;Andy3;Andy4
02         Steven1;Steven2;Steven3;Steven4

該條SQL語句的編寫思想是:
1)根據分組後的行號,構造一棵樹(或者多棵)。
2)把從根到葉子的值串接起來。


二、列變行
1.重新構造測試表test,並初始化實驗資料
sec@ora10g> drop table test purge;
sec@ora10g> create table test (name_id varchar2(10), name varchar2(40));
sec@ora10g> insert into test values ('01','Andy1;Andy2;Andy3;Andy4');
sec@ora10g> insert into test values ('02','Steven1;Steven2;Steven3;Steven4');
sec@ora10g> commit;

2.檢視測試表資料
sec@ora10g> select * from test;

NAME_ID    NAME
---------- ----------------------------------------
01         Andy1;Andy2;Andy3;Andy4
02         Steven1;Steven2;Steven3;Steven4

3.行變列轉換的SQL語句如下
SELECT   t.name_id,
         SUBSTR (t.name,
                 INSTR (';' || t.name, ';', 1, rn),
                   INSTR (t.name || ';', ';', 1, rn)
                 - INSTR (';' || t.name, ';', 1, rn)
                ) name
    FROM (SELECT a.name_id, a.name, b.rn
            FROM test a,
                 (SELECT ROWNUM rn
                    FROM DUAL
                  CONNECT BY ROWNUM <= 100) b
           WHERE INSTR (';' || a.name, ';', 1, rn) > 0) t
ORDER BY 1, 2;


NAME_ID    NAME
---------- ----------------------------------------
01         Andy1
01         Andy2
01         Andy3
01         Andy4
02         Steven1
02         Steven2
02         Steven3
02         Steven4

8 rows selected.

該條SQL語句的編寫思想
1)構造虛擬表把源資料的行數增加
2)根據行號選擇顯示欄位的不同部分

secooler
10.09.27

-- The End --

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/519536/viewspace-609167/,如需轉載,請註明出處,否則將追究法律責任。

相關文章