I have table Users which contains columns Login and Phone and I have table GeoPhone which contains columns Mask and Region.
Phone is stored as varchar (“+380981234567”). Mask is stored as varchar (“+38098”). Masks are overlapped, for instance, +380 and +38098.
I need a View that joins Users and GeoPhone tables and assigns Region for each Login by longest matched Mask.
I wrote SQL statement below but result contains duplicated Logins and I do not know how to avoid this:
SELECT TOP (5000)
Users.Login, Users.Phone, GeoPhone.Region, LEN(GeoPhone.Mask) AS MaskLen
FROM Users
INNER JOIN GeoPhone ON LEFT(Users.Phone, LEN(GeoPhone.Mask)) = GeoPhone.Mask
ORDER BY Users.Login, MaskLen DESC
Please help to improve it.
One way to do this is to use Cross Apply in SQL 2005 or later.
You should note that it only returns one record from geophone. If there are two records in geophone.mask that tie for the length of mask you won’t be able to determine which record it will return
Here’s a solution that uses MAX() and its realtively portable
However if two rows in geophone Tie for longest length both results will be returned. I don’t know if this is better or worse for you.
You can also use ROW_NUMBER in SQL 2005 or later