Oracle10g SQL pivot

2019-01-15 23:10发布

I have a table named TABLE for example looking like:

ID  | email
--------------
1   |  a@a.com 
1   |  b@b.com
2   |  c@c.com
3   |  d@d.com
3   |  e@e.com

and I would like to return something like

ID | email1 | email2
--------------------
1  | a@a.com| b@b.com
2  | c@c.com|
3  | d@d.com| e@e.com

I was wondering how I could use pivoting to help me get rid of duplicate ID rows and just add an extra column for their other emails. Thanks for the help.

SELECT id, email1, email2, email3
FROM (
SELECT id, 
        email, 
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY email) AS emailRank
FROM TABLE
) 
pivot( max(email) FOR emailRank IN (1 as email1, 2 as email2, 3 as email3));

Edit: fixed above thanks to beach's answer

2条回答
女痞
2楼-- · 2019-01-15 23:41

You can use a procedure or a combination of group by rownum and decode. Personally, I find the procedure approach cleaner.

See: http://asktom.oracle.com/pls/apex/f?p=100:11:0::NO::P11_QUESTION_ID:15151874723724

查看更多
时光不老,我们不散
3楼-- · 2019-01-15 23:49

I prefer using the GROUP BY solution with CASE expression.

SELECT 
    id,
    MAX(CASE WHEN emailRank = 1 THEN email END) AS [1],
    MAX(CASE WHEN emailRank = 2 THEN email END) AS [2],
    MAX(CASE WHEN emailRank = 3 THEN email END) AS [3],
    MAX(CASE WHEN emailRank = 4 THEN email END) AS [4]
FROM (
    SELECT
        id, 
        email, 
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY email) AS emailRank
    FROM TABLE
)
GROUP BY id;

Original Pivot example had type and missing ")". Try the following to get pivot working:

pivot( max(email) FOR emailRank IN (1,2,3));
查看更多
登录 后发表回答