0

Newbie to SQL here and need a bit of guidance. Any would be appreciated!

So say I have a SQL table as follows:

id  email            preference
1   [email protected]   cake
1   [email protected]   fruit
1   [email protected]   cheese
1   [email protected]   sauce
2   [email protected]   cake
2   [email protected]   sauce
3   [email protected]   tea

What I want to do is merge the duplicate records (based on id and email), but also use the duplicate data in the "preferences" column to populate some additional columns in a new table. Basically I want to get to this:

id  email           preference1   preference2   preference3   preference4 
1   [email protected]  cake          fruit         cheese        sauce
2   [email protected]  cake          sauce         null          null
2   [email protected]  tea           null          null          null

Currently at a bit of a loss of how to get here.

2
  • Tag your question with the database you are using. Commented Dec 9, 2020 at 3:13
  • Have you considered another table with a different structure like (id, person_id, preference)? This can allow you to see all the preferences of an individual and respect 2nd Normal Form. Commented Dec 9, 2020 at 3:18

1 Answer 1

2

If you know you have four preferences, you can use conditional aggregation with row_number():

select id, email,
       max(case when seqnum = 1 then preference end) as preference_1,
       max(case when seqnum = 2 then preference end) as preference_2,
       max(case when seqnum = 3 then preference end) as preference_3,
       max(case when seqnum = 4 then preference end) as preference_4
from (select t.*,
             row_number() over (partition by id, email order by preference) as seqnum
      from t
     ) t
group by id, email;
Sign up to request clarification or add additional context in comments.

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.