我正在使用Oracle,我希望将一个查询转换为多行。
这是我的疑问:
SELECT I.cd_curso,
I.cd_discip,
ND.ds_discip,
I.cd_turma_t,
I.cd_turma_p,
I.cd_turma_l,
I.cd_turma_tp,
I.cd_turma_e,
I.cd_turma_o,
I.cd_turma_c,
I.cd_turma_s,
Count(*) AS alunos
FROM cse.v_vwinscri I,
cse.t_tbdiscip ND
WHERE I.cd_lectivo = 201314
AND I.cd_discip = 911901
AND I.cd_discip = ND.cd_discip
AND I.cd_curso = 9885
AND ( I.cd_turma_t IS NOT NULL
OR I.cd_turma_p IS NOT NULL
OR I.cd_turma_l IS NOT NULL
OR I.cd_turma_tp IS NOT NULL
OR I.cd_turma_e IS NOT NULL
OR I.cd_turma_o IS NOT NULL
OR I.cd_turma_c IS NOT NULL
OR I.cd_turma_s IS NOT NULL )
GROUP BY I.cd_curso,
I.cd_discip,
ND.ds_discip,
I.cd_turma_t,
I.cd_turma_p,
I.cd_turma_l,
I.cd_turma_tp,
I.cd_turma_e,
I.cd_turma_o,
I.cd_turma_c,
I.cd_turma_s
ORDER BY I.cd_curso,
I.cd_turma_t,
I.cd_turma_p,
I.cd_turma_l,
I.cd_turma_tp,
I.cd_turma_e,
I.cd_turma_o,
I.cd_turma_c,
I.cd_turma_s
我希望将结果CD_TURMA_T,CD_TURMA_P等转换为CD_TURMA的不同行。基本上使用第一个fiels作为键,其他作为值,将它们从列更改为行...
有可能吗?
答案 0 :(得分:1)
您可以像这样简单地使用UNION ALL
:
WITH cte AS (
SELECT I.cd_curso,
I.cd_discip,
ND.ds_discip,
I.cd_turma_t,
I.cd_turma_p,
I.cd_turma_l,
I.cd_turma_tp,
I.cd_turma_e,
I.cd_turma_o,
I.cd_turma_c,
I.cd_turma_s,
Count(*) AS alunos
FROM cse.v_vwinscri I,
cse.t_tbdiscip ND
WHERE I.cd_lectivo = 201314
AND I.cd_discip = 911901
AND I.cd_discip = ND.cd_discip
AND I.cd_curso = 9885
AND ( I.cd_turma_t IS NOT NULL
OR I.cd_turma_p IS NOT NULL
OR I.cd_turma_l IS NOT NULL
OR I.cd_turma_tp IS NOT NULL
OR I.cd_turma_e IS NOT NULL
OR I.cd_turma_o IS NOT NULL
OR I.cd_turma_c IS NOT NULL
OR I.cd_turma_s IS NOT NULL )
GROUP BY I.cd_curso,
I.cd_discip,
ND.ds_discip,
I.cd_turma_t,
I.cd_turma_p,
I.cd_turma_l,
I.cd_turma_tp,
I.cd_turma_e,
I.cd_turma_o,
I.cd_turma_c,
I.cd_turma_s)
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_t AS cd_trauma,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_p,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_l,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ND.ds_discip,
cd_turma_tp,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_e,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_o,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_c,
alunos
FROM cte
UNION ALL
SELECT cd_curso,
cd_discip,
ds_discip,
cd_turma_s,
alunos
FROM cte;