Question

I have two tables one in my current system that has the current email, and one that I have created and exported all the email addresses from the Global Address Book, along with a BIT value for which is the primary email address and a user id value. I wrote a query using sub querys to find what email addresses should change, but I though I should be able to do this without using sub querys but couldn't figure out how?

Does anyone know how or if this could be done better without using sub queries?

What I have works but I want to learn how to write SQL better.

I though I should have been able to do this using OVER (Partition BY Member_ID) and MAX(CAST( [primary] AS int)), but spent a few hours trying to figure it out and was unsucsessful.

User_Emails
{
email varchar(75)
}

eg:
User_Emails
bob@oldemail.com
sue@evenolderemail.com
jim@otheremail.com
bill@oldemail.com

...

Global_Address_Book
{
Member_ID int
primary BIT
email_address varchar(75)
}

eg:
Member_ID        | primary | email_address
1                | 1       | bob@newemail.com
1                | 0       | bob@reallyoldemail.org
1                | 0       | bob@oldemail.com
2                | 1       | sue@newemail.com
2                | 0       | sue@oldemail.com
2                | 0       | sue@reallyoldemail.org
2                | 0       | sue@evenolderemail.com
3                | 1       | bill@newemail.com
3                | 0       | bill@oldemail.com
4                | 1       | jan@alternativeemail.com

...

SELECT Changed_Email_list.email AS Old_Email, New_Email_List.email_address AS New_Email
FROM (SELECT Member_ID, email
      FROM [Database].[Global_Address_Book] INNER JOIN [Database].[User_Emails]
       ON [Global_Address_Book].[email_address] = [User_Emails].[email]) AS     
      Changed_Email_list LEFT JOIN 
      (SELECT Member_ID, email_address 
       FROM [Database].[Global_Address_Book]
       WHERE [primary] = 1) AS New_Email_List
       ON Changed_Email_list.Member_ID = New_Email_List.Member_ID
Was it helpful?

Solution

this should do i guess

select UserEmails.Email as OldEmail,GAB.Email as NewEamil
from   UserEmailsfromAddressBook  
inner join UserEmails on UserEmails.Email=UserEmailsfromAddressBook.Email
      and isprimary =0
inner join UserEmailsfromAddressBook  GAB on GAB.memberId=UserEmailsfromAddressBook.memberID
     and GAB.isprimary=1

test script in sqlfiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top