# Oracle 行列转置

1、固定列数的行列转换 如 student subject grade --------- ---------- -------- student1 语文 80 student1 数学 70 student1 英语 60 student2 语文 90 student2 数学 80 student2 英语 100 …… 转换为 语文 数学 英语 student1 80 70 60 student2 90 80 100 …… 语句如下：

```SELECT   student, SUM (DECODE (subject, '语文', grade, NULL)) "语文",
SUM (DECODE (subject, '数学', grade, NULL)) "数学",
SUM (DECODE (subject, '英语', grade, NULL)) "英语"
FROM table1
GROUP BY student;```

2、不定列行列转换 如 c1 c2 --- ----------- 1 我 1 是 1 谁 2 知 2 道 3 不 …… 转换为 1 我是谁 2 知道 3 不

```CREATE OR REPLACE FUNCTION get_c2 (tmp_c1 NUMBER)
RETURN VARCHAR2
IS
col_c2   VARCHAR2 (4000);
BEGIN
FOR cur IN (SELECT c2
FROM t
WHERE c1 = tmp_c1)
LOOP
col_c2 := col_c2 || cur.c2;
END LOOP;

col_c2 := RTRIM (col_c2, 1);
RETURN col_c2;
END;

SELECT DISTINCT c1, get_c2 (c1) cc2
FROM table1;```

```SELECT     c1, SUBSTR (MAX (SYS_CONNECT_BY_PATH (c2, ';')), 2) NAME
FROM (SELECT c1, c2, rn, LEAD (rn) OVER (PARTITION BY c1 ORDER BY rn)
rn1
FROM (SELECT c1, c2, ROW_NUMBER () OVER (ORDER BY c2) rn
FROM t))
CONNECT BY rn1 = PRIOR rn
GROUP BY c1;```

1. CREATE TABLE wm_test
2. (
3. code NUMBER,
4. name1 VARCHAR2 (100),
5. seq NUMBER
6. );
7. INSERT INTO wm_test
8. VALUES (1, 'a', 1);
9. INSERT INTO wm_test
10. VALUES (1, 'b', 2);
11. INSERT INTO wm_test
12. VALUES (1, 'c', 3);
13. INSERT INTO wm_test
14. VALUES (2, ' 中', 1);
15. INSERT INTO wm_test
16. VALUES (2, '国', 2);
17. INSERT INTO wm_test
18. VALUES (2, '人', 3);
19. COMMIT;
20. CREATE OR REPLACE VIEW v1
21. AS
22. SELECT code, name1
23. FROM (SELECT code,
24. name1,
25. ROW_NUMBER ()
26. OVER (PARTITION BY code ORDER BY LENGTH (name1) DESC)
27. rn2
28. FROM ( SELECT code, SYS_CONNECT_BY_PATH (name1, '^') name1
29. FROM (SELECT code,
30. name1,
31. rn,
33. OVER (PARTITION BY code ORDER BY rn)
34. rn1
35. FROM (SELECT code,
36. name1,
37. ROW_NUMBER ()
38. OVER (ORDER BY code, seq DESC)
39. rn
40. FROM wm_test))
42. CONNECT BY rn1 = PRIOR rn))
43. WHERE rn2 = 1;
44. SELECT * FROM v1;

[sql] view plain copy

1. -- name1如果有顺序，则按照其seq排序
2. SELECT code, LTRIM (MAX (SYS_CONNECT_BY_PATH (name1, '^')), '^') name1
3. FROM wm_test
5. CONNECT BY seq = PRIOR seq + 1 AND code = PRIOR code
6. GROUP BY code;
7. -- name1如果没有顺序，则按照rowid排序
8. SELECT code, LTRIM (MAX (SYS_CONNECT_BY_PATH (name1, '^')), '^') name1
9. FROM (SELECT code,
10. name1,
11. ROW_NUMBER () OVER (PARTITION BY code ORDER BY ROWID) rn1
12. FROM wm_test)
14. CONNECT BY rn1 = PRIOR rn1 + 1 AND code = PRIOR code
15. GROUP BY code;