I am thinking I am getting close but not sure:
I have an example Table containing email address, Personal and Work.
I am trying to create a new table which holds a single address.
Then insert an email address, example: If a user has a work email but no personal email, the insert work email and if no work email, insert personal email.
The following code does not work but it’s just to show some of the many variations I have used:
USE EXAMPLE_DB
GO
CREATE TABLE USER_EMAIL(
USER_NBR CHAR(1) NOT NULL
,EMAIL VARCHAR(30)NULL
)
GO
INSERT INTO USER_EMAIL(
USER_NBR
,EMAIL
)
SELECT USER_NBR
,CASE WHEN EMAIL_ADDR IS NULL AND EMAIL_TYPE = 'Personal' THEN EMAIL_TYPE = 'Work' END EMAIL
,CASE WHEN EMAIL_ADDR IS NULL AND EMAIL_TYPE = 'Work' THEN EMAIL_TYPE = 'Personal' END EMAIL
FROM EMAIL_DATA
Here is the table for the EMAIL_DATA:
USER_NBR EMAIL_TYPE EMAIL_ADDR
1 Personal
2 Personal user2personal@demo.com
3 Personal user3personal@demo.com
4 Personal
5 Personal user5personal@demo.com
1 Work user1work@demo.com
2 Work user2work@demo.com
3 Work
4 Work user4work@demo.com
5 Work
Thanks everyone!
Here’s an example using
row_number:Since there are just two email types, you could also use
left jointwice:Another approach that looks up the preferred email address using
cross apply: