我正在使用oracle sql开发人员,并尝试基于IssueId进行透视,并希望获得一行。但是它为问题的空值创建了一个额外的行,但我希望所有值都在一行中。请,请参见下面的情况,以更好地解释此令人困惑的问题。
加入后我拥有的表:
数据:
带有多余空行的当前结果:
预期结果:
我的查询
select *
from
(
select TableB.SEQ_ID,TableA.ISSUEID , TableC.Question
from TableC RIGHT JOIN TableB ON TableC.QUESTIONID = TableB.QUESTION_ID
LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND ISSUEID = 3250
) d
pivot
(
MAX(Question)
for SEQ_ID in ( 1, 2, 3 ,4, 5 )
) piv;
任何与此相关的建议,我们将不胜感激。谢谢!
答案 0 :(得分:1)
假设中间结果集是您希望看到的,而左/右外部联接对于您要执行的操作是必需的,则可以使用表A替换表A中不匹配的行中的空问题ID。解析聚合:
max(TableA.ISSUEID) over () as ISSUEID
使用与您显示的中间结果相同的示例数据,修改后的内部查询:
select TableB.SEQ_ID, max(TableA.ISSUEID) over () as ISSUEID, TableC.Question
from TableC
RIGHT JOIN TableB ON TableC.QUESTIONID = TableB.QUESTION_ID
LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND TableA.ISSUEID = 3250;
获取
SEQ_ID ISSUEID QUESTION
---------- ---------- -------------
1 3250 How are You?
2 3250 Hows it going
3 3250 Is It Okay?
4 3250 Whats Up?
5 3250 Really?
并且在旋转时:
select *
from
(
select TableB.SEQ_ID, max(TableA.ISSUEID) over () as ISSUEID, TableC.Question
from TableC
RIGHT JOIN TableB ON TableC.QUESTIONID = TableB.QUESTION_ID
LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND TableA.ISSUEID = 3250
) d
pivot
(
MAX(Question)
for SEQ_ID in ( 1, 2, 3 ,4, 5 )
) piv;
获取
ISSUEID 1 2 3 4 5
---------- ------------- ------------- ------------- ------------- -------------
3250 How are You? Hows it going Is It Okay? Whats Up? Really?
您可以通过以下方式获得相同的结果:
select * from (
select b.seq_id, a.issueid, c.question
from tableb b
join tablec c on c.questionid = b.question_id
cross join (
select issueid from tablea where issueid = 3250
) a
) d
pivot
(
max(question)
for seq_id in (1, 2, 3 ,4, 5)
);
(或12c +中的cross apply
),也可以在条件>= 3250
下使用。这只会针对每个匹配的问题ID列出所有五个问题。那实际上可能不是您想要的,但这是您非常有限的样本数据和预期结果所暗示的。
答案 1 :(得分:0)
如果您只想要有效的问题,请不要把所有这些外部联接弄乱。只需从具有要保留的行的表开始,其他表我们以left join
开始,然后过滤where
子句中的第一个表:
from (select TableB.SEQ_ID, TableA.ISSUEID , TableC.Question
from TableA LEFT JOIN
TableB
on TableB.QUESTION_ID = TableA.QUESTIONID LEFT JOIN
TableC
on TableC.QUESTIONID = TableB.QUESTION_ID
where tableA.ISSUEID = 3250
) d