I’m trying to write a query that will return the closest match from a table. The table represents a hierarchy, and looks like this:
Hier_Code Group1 Group2 Group3
_________ ______ ______ ______
A 1 1 5
AA 1 2 5
AAA 1 2 5
AAB 1 3 5
AB 2 3 5
ABA 2 3 5
ABB 2 3 5
The values I’m searching for may not match perfectly, in which case I’d want them to ‘roll-up’ to the next level to find the match. For example:
Value Returns:
A 1 1 5 (Perfect match)
AAC 1 2 5 (AA is closest)
AABB 1 3 5 (AAB is closest)
The idea is that you would strip off one character at a time from the search term until you find a match. I’ve tried doing this with a recursive CTE, and also with a WHILE loop to no avail.
Any suggestions?
Thanks in advance
Try this: