I am looking to join two tables where there's a 90% match for example.
Taking the example below, I want to join table A and table B on the phone number. You can see that the phone numbers differ slightly (the international code). I'd like the end result to show as table C.
I imagine it'll be something like but the join would specify to match on 90% of the phone_number
select
a.*,
b.most_recent_booking_date
from a
left join b
on a.phone_number = b.phone_number
Hope that's clear and any help would be great! Cheers!
Table A
Phone number | Most recent call date |
---|---|
441234567891 | 01/05/22 |
441234567892 | 02/05/22 |
Table B
Phone number | Most recent booking date |
---|---|
+441234567891 | 03/05/22 |
+441234567892 | 04/05/22 |
Table C
Phone number | Most recent call date | Most recent bookingdate |
---|---|---|
441234567891 | 01/05/22 | 03/05/22 |
441234567892 | 02/05/22 | 04/05/22 |
You can try something like this, but I don't like it, as Demeteor says you should have an ID to join on. Note that I use a left join here, in case there is no data in table #T2. I was also considering a computed column where it removes the + and then you could join that way too. I will also get told off for SQL injection if the phone number could be dodgy.
CREATE TABLE #T1 (
PhoneNumber VARCHAR(20) NOT NULL,
CallDate DATE NOT NULL
);
CREATE TABLE #T2 (
PhoneNumber VARCHAR(20) NOT NULL,
BookingDate DATE NOT NULL
);
INSERT INTO #T1 (PhoneNumber, CallDate)
VALUES
('441234567891', '20220501'),
('441234567892', '20220502');
INSERT INTO #T2 (PhoneNumber, BookingDate)
VALUES
('+441234567891', '20220503'),
('+441234567892', '20220504');
GO
SELECT *
FROM #T1 AS T1
LEFT JOIN #T2 AS T2 ON T2.PhoneNumber LIKE '%' + T1.PhoneNumber;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.