I have a table with the following columns in SQL Server:
MEMBERID, MEMBEREMAIL, FATHEREMAIL, MOTHEREMAIL, MEMBERNAME
MEMBERID is PK. The three email columns are not unique, so the same email may appear several times in the same row AND in several rows.
I am trying to extract a unique list of emails, and for each email also get a memberid and membername (it does not matter from which record).
For example if I have three rows:
1 x@x.com y@y.com y@y.com Mark
2 z@z.com y@y.com x@x.com John
3 x@x.com y@y.com z@z.com Susan
I want to get the three emails (x@x.com, y@y.com, z@z.com) and for each of those a MEMBERID in which they appear. It does NOT which MEMBERID (for example for x@X.com I don’t care if I get the values 1 and Mark or 2 and John or 3 and Susan, as long as x@x.com appears only once in the results.
If I use DISTINCT when trying to return the email and memberid and membername, of course I get all of the rows.
You could use a subquery to normalize all emails. Then you can use
row_numberto filter out onememberid, membernameper email:You could also normalize the emails using the
UNPIVOTclause, like this:Try both versions at SQL Fiddle:
UNION ALLversionUNPIVOTversion