当列类型是集合时,是否可以将行转置为列?
请考虑以下事项:
CREATE TABLE dept (dept_no number(1), job_id VARCHAR2(2), VALUE VARCHAR2(1))
INSERT INTO dept
select 2 dept_no,'J1' jobid, 'X' VALUE from dual
union all
select 2 dept_no,'J2' jobid, 'Y' VALUE from dual
union all
select 2 dept_no,'J2' jobid, 'Z' VALUE from dual
union all
select 3 dept_no,'J1' jobid, 'Y' VALUE from dual
union all
select 3 dept_no,'J1' jobid, 'X' VALUE from dual
union all
select 3 dept_no,'J2' jobid,'X' VALUE from dual
union all
select 3 dept_no,'J3' jobid,'Z' VALUE from dual
union all
select 3 dept_no,'J3' jobid,'X' VALUE from dual
union all
select 3 dept_no,'J3' jobid,'Y' VALUE from dual
CREATE OR REPLACE TYPE v_t AS TABLE OF VARCHAR2(1);
我无法使用MAX OR MIN对集合进行分组。
select dept_no,
decode(job_id,'J1',valueList) J1,
decode(job_id,'J2',valueList) J2,
decode(job_id,'J3',valueList) J3
from (SELECT dept_no, job_Id, CAST(COLLECT(VALUE) AS v_t ) AS valueList
FROM dept
GROUP BY dept_no, job_Id)
输出:
DEPT_NO J1 J2 J3
---------- ------------------ ------------------ ------------------
2 V_T('X')
2 V_T('Y', 'Z')
3 V_T('Y', 'X')
3 V_T('X')
3 V_T('Z', 'Y', 'X')
预期产出:
DEPT_NO J1 J2 J3
---------- ----------------- ----------------- --------------------
2 V_T('X') V_T('Y', 'Z') V_T()
3 V_T('Y', 'X') V_T('X') V_T('Z', 'Y', 'X')
dept_no可能是组列吗?
更新:抱歉,我找到了答案
SELECT dept_no, CAST(COLLECT(decode(job_id, 'J1', VALUE, NULL)) AS v_t) J1,
CAST(COLLECT(decode(job_id, 'J2', VALUE, NULL)) AS v_t) J2,
CAST(COLLECT(decode(job_id, 'J3', VALUE, NULL)) AS v_t) J3
FROM dept
GROUP BY dept_no