优化行到列的转换

时间:2014-07-24 10:05:51

标签: sql performance oracle inner-join

我有一个大的Oracle表(大约4000万行),如下所示:

ID  Name    Question Answer Reason      
3   Name1   1       Yes     blah blah
3   Name1   2       No      NA
3   Name1   3       No      NA
3   Name1   4       Yes     blah2
3   Name1   5       Yes     null
3   Name1   6       Yes     blah3
3   Name1   7       No      null
6   Name2   1       Yes     blah4444
6   Name2   2       No      null
6   Name2   3       Yes     blah3
6   Name2   4       NA      blah5
6   Name2   5       Yes     null
6   Name2   6       Yes     blah6
6   Name2   7       NA      null

我需要每个ID一行,即我需要为每个问题的答案添加列(每个ID有7个问题)和每个问题的原因。我需要让它看起来像这样:

ID  Name    Q1     Q1-Reason    Q2    Q2-Reason   Q3    Q3-Reason    etc.
3   Name1   Yes    blah blah    No    null      
6   Name2   Yes    blah4444     No    null      

我的查询目前看起来像这样:

select
   A.ID,A.NAME,B1.Q1,B1.Q1-REASON,B2.Q2,B2.Q2-REASON
from
   TABLENAME A
inner join
    (
    select distinct C1.ID,C1.ANSWER as Q1,C1.REASON as Q1-REASON
    from TABLENAME C1
    where C1.QUESTION=1
    ) B1 on B1.ID=A.ID
inner join
    (
    select distinct C2.ID,C2.ANSWER as Q2,C2.REASON as Q2-REASON
    from TABLENAME C2
    where C2.QUESTION=2
    ) B2 on B2.ID=A.ID
...
...

但是,由于表格很大,因此需要花费很长时间来检索数据。有人可以建议优化此查询的方法吗?

我使用的是Oracle 10g和SQLDeveloper 4.0.2.15

1 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT
    TABLENAME.ID,
    TABLENAME.Name,
    MAX(CASE WHEN TABLENAME.Question=1 THEN TABLENAME.Answer ELSE NULL END) AS Q1,
    MAX(CASE WHEN TABLENAME.Question=1 THEN TABLENAME.Reason ELSE NULL END) AS Q1_Reason,
    MAX(CASE WHEN TABLENAME.Question=2 THEN TABLENAME.Answer ELSE NULL END) AS Q2,
    MAX(CASE WHEN TABLENAME.Question=2 THEN TABLENAME.Reason ELSE NULL END) AS Q2_Reason,
    MAX(CASE WHEN TABLENAME.Question=3 THEN TABLENAME.Answer ELSE NULL END) AS Q3,
    MAX(CASE WHEN TABLENAME.Question=3 THEN TABLENAME.Reason ELSE NULL END) AS Q3_Reason
/*And so on*/
FROM
    TABLENAME
GROUP BY
    TABLENAME.ID,
    TABLENAME.Name