Skip to content
Advertisement

TSQL – New column value based on other columns with highest level of match

So I’ve got a mapping table with the following information:

And another fact table with the following info:

Ideally I should add CCode in the fact table with the highest matching value of Number (first) & FCODE (second)

So for example the first record: Number: 0123456789 FCode: 12345 should result to have value CCode 6 to be added in the fact table

If number is 0129456789 & FCode 12345, CCode should become 4.

I tried working with a RANK function, but I’m missing something but cannot see what

Here is the SQL query I have, but does not do what I expected..

Any support is appreciated. Thanks in advance!

Advertisement

Answer

You can use values from the mapping table as regular expression patterns to match against values in a fact table.

And if i understand correctly, you need to get maximum CCODE for both matches mapping.Number with fact.Number and mapping.FCode with fact.FCode.

If so, you can select TOP 1 of matching rows from mapping table sorted by CCODE in descending order.

To get a final result you can use OUTER APPLY like this

Please, check a demo.

Result:

Number     | FCode  | CCode
:--------- | :----- | ----:
0123456789 | 12345  |     6
0123456789 | 545243 |     3
0129456789 | 545243 |     3
0129456789 | 12345  |     4

As per @HABO comment, to retain pattern’s length and symbol order, it’s more correct to use an underscore to replace an asterisk in the pattern. And then query would be like this

Working demo.

This query produces NULL as CCode for second and third rows in fact table, because there is no any match in the mappings table.

Number     | FCode  | CCode
:--------- | :----- | ----:
0123456789 | 12345  |     6
0123456789 | 545243 |  null
0129456789 | 545243 |  null
0129456789 | 12345  |     4
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement