79727007

Date: 2025-08-06 08:25:59
Score: 1
Natty:
Report link

I am answering this on the assumption that you are not writing a financial application, but just want something for personal use and you have data in a certain form, which it is not worth reworking.

Essentially what you want to do, is to get a "best match". Tesco and Tesco Pet Insurance matches your current query, but you want the best fit. One way to do this is to select a third column, which replaces the Payee inside the Description with nothing. The resultant column with the shortest length (i.e. the one where Payee has replaced the most) is the best fit.

Using this technique, something like the following should do the trick:

declare @tbltxns table ([Description] nvarchar(100), Amount decimal(10,2));
declare @tblPayee table (Payee nvarchar(100));

INSERT INTO @tbltxns VALUES
('Tesco Pet Insurance Dog Health Care Year Premium', 250.0),
('MyFitness Gym Monthly fee', 30.0);

INSERT INTO @tblPayee VALUES
('Tesco'),
('Tesco Pet Insurance'),
('MyFitness');

WITH CTE AS
(SELECT
    tx.[Description], py.Payee, REPLACE(tx.[Description], py.Payee, '') AS NoPayee
FROM @tblTxns TX
INNER JOIN @tblPayee py
    ON CHARINDEX(py.Payee, tx.Description, 1) > 0),
CTE2 AS 
(SELECT c.[Description], c.Payee, ROW_NUMBER() OVER(PARTITION BY c.[Description] ORDER BY LEN(c.NoPayee)) rn
FROM CTE c)
SELECT c2.[Description], c2.Payee
FROM CTE2 c2
WHERE rn = 1;

For future reference, when asking a database question, please provide table definitions and sample data along the lines that I have used. Just as an illustration, I am using table variables, as they don't have to be deleted, but CREATE TABLE would be quite acceptable. Sample data in the form of INSERT statements is desirable. Why? Simply so that people here are spared a bit of time and effort, in trying to provide you with a workable answer.

Reasons:
  • Blacklisted phrase (0.5): Why?
  • RegEx Blacklisted phrase (2.5): please provide
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • High reputation (-1):
Posted by: Jonathan Willcock