2

let's say I have:

User     Email
 1       [email protected]
 1       [email protected]
 1       [email protected]
 2       [email protected]
 2       [email protected]
 3       [email protected]

and I want the output:

 User     Eamil1            Email2          Email3
 1        [email protected]     [email protected]   [email protected]
 2        [email protected]     [email protected]   
 3        [email protected]

I found other answers about using FOR XML Path, but that's not what I want. it combines rows into one column, and separate the values with ';'

I also tried JOIN the table with itself, and it's also not the result I want.

Any help is appreciated.

1
  • 1
    May I ask what is your intention for doing this? Commented Oct 14, 2014 at 21:54

2 Answers 2

2

Try something like this. Pivot is not a good solution in this case. Pivot is not efficient for non numeric values.

WITH C AS(
    SELECT 
    RANK() OVER (PARTITION BY [User] ORDER BY Email) AS [Rank]
    ,[User], Email
    FROM Emails
)
SELECT [User]
    ,MIN(CASE C.[Rank] WHEN 1 THEN Email END) AS [Email1]
    ,MIN(CASE C.[Rank] WHEN 2 THEN Email END) AS [Email2]
    ,MIN(CASE C.[Rank] WHEN 3 THEN Email END) AS [Email3]
FROM C
GROUP BY [User]
Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean pivot is not efficient for non numerical values?
i will give this a try. i did some research on pivot. pivot mostly works well if you need to SUM/AVG int values on results. I haven't been able to get a way to make it work on email addresses yet.
@triston You can use PIVOT on an an email address, you'll just need to use the aggregate function max or min on the column since it is a string.
0

You should look into the PIVOT command.

http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.