a full outer join on the item_id and alternate_code should do the trick.
SELECT COALESCE([a].[item_id], [b].[item_id]) as item_id,
[a].[alternate_code_ERP],
[b].[web_alternate_code]
FROM [alt_code_ERP] AS [a]
FULL OUTER JOIN [web_alt_code] AS [b]
ON [a].[item_id] = [b].[item_id]
AND [a].[alternate_code_ERP] = [b].[web_alternate_code];
This will get your result set, though I did add the Name field for clarity. The common table expression (cte) with ROW_NUMBER() will get the email priority. Then I left joined that back to the base table to return the names and a NULL for Julius.
CREATE TABLE #emailOrPhone (ID INT IDENTITY(1,1), Type INT, Number VARCHAR(50), Name VARCHAR(20))
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1011,'(215)555-1213','Sally')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1011,'(215)555-1312','Sally')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1012,'sally@ourdomain.com','Sally')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1013,'sallyf@gmail.com','Sally')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1013,'frankiebaby@yahoo.com','Frank')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1013,'franks@ibm.com','Frank')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1010,'555-123-9876','Julius')
INSERT INTO #emailOrPhone (Type, Number, Name) VALUES (1011,'425-369-1470','Julius')
;WITH cte AS
(
SELECT Name, Number
, CASE WHEN Number like '%@ourdomain.com' THEN 1 ELSE 2 END AS 'emailPriority'
, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Name) as rn
FROM #emailOrPhone
WHERE Number like '%@%'
)
SELECT DISTINCT Names.Name, Emails.Number
FROM #emailOrPhone as Names
LEFT JOIN cte as Emails on Names.Name = Emails.Name and Emails.rn = 1
ORDER BY Names.Name, Emails.Number
DROP TABLE #emailOrPhone
Best Answer
You could also split the string and then search on the splitted values. An example could be by creating and using this function.
Starting from SQL Server 2016 you could use the built in
STRING_SPLIT()
function.Creating the function from the blogpost and executing this query afterwards
Result
DB<>Fiddle
An optimization could be proactively splitting the table into a permanent one so you don't need to do splitting on the entire table everytime. (If the values are static)
EDIT
Comment by @Erikdarling
The function by Jeff Moden
After creating the function in his blogpost, you could use a query that resembles the previous one.
DB<>Fiddle