我的桌子 - 学生的形式是
Student Subject1 Subject2
A 123 1
B 4
C 122
我想获取学生的所有非空记录以及列名 注意:只应显示非空记录
所以当我查询学生A时,我应该
Subject1 123
Subject2 1
当我查询学生B时,我应该
Subject2 4
当我查询学生C时,我应该得到 Subject1 122
我想动态生成列名。 谢谢你的帮助!
答案 0 :(得分:0)
这可以按照以下方式完成 -
SELECT *
FROM
(
WITH A AS
(
SELECT 'A' AS STUDENT, 123 AS SUBJECT1, 1 AS SUBJECT2 FROM DUAL
UNION
SELECT 'B' AS STUDENT, NULL AS SUBJECT1, 4 AS SUBJECT2 FROM DUAL
UNION
SELECT 'C' AS STUDENT, 122 AS SUBJECT1, NULL AS SUBJECT2 FROM DUAL
)
SELECT *
FROM
A
UNPIVOT
(
MARKS FOR SUBJECT IN (SUBJECT1, SUBJECT2)
)
)
WHERE
STUDENT = 'A';
输出 -
STUDENT,SUBJECT,MARKS
A,SUBJECT1,123
A,SUBJECT2,1