Search code examples
sqllogicbusiness-logic

Approaches to converting a table of possibilities into logical statements


I'm not sure how to express this problem, so my apologies if it's already been addressed.

I have business rules summarized as a table of outputs given two inputs. For each of five possible value on one axis, and each of five values on another axis, there is a single output. There are ten distinct possibilities in these 25 cells, so it's not the case that each input pair has a unique output.

I have encoded these rules in TSQL with nested CASE statements, but it's hard to debug and modify. In C# I might use an array literal. I'm wondering if there's an academic topic which relates to converting logical rules to matrices and vice versa.

As an example, one could translate this trivial matrix:

   A  B  C
-- -- -- --
X  1  1  0
Y  0  1  0

...into rules like so:

if B OR (A and X) then 1 else 0

...or, in verbose SQL:

CASE WHEN FieldABC = 'B'                   THEN 1
     WHEN FieldABX = 'A' AND FieldXY = 'X' THEN 1
     ELSE 0

I'm looking for a good approach for larger matrices, especially one I can use in SQL (MS SQL 2K8, if it matters). Any suggestions? Is there a term for this type of translation, with which I should search?


Solution

  • Sounds like a lookup into a 5x5 grid of data. The inputs on axis and the output in each cell:

        Y=1 Y=2 Y=3 Y=4 Y=5
    x=1  A   A   D   B   A
    x=2  B   A   A   B   B
    x=3  C   B   B   B   B
    x=4  C   C   C   D   D
    x=5  C   C   C   C   C
    

    You can store this in a table of x,y,outvalue triplets and then just do a look up on that table.

    SELECT OUTVALUE FROM BUSINESS_RULES WHERE X = @X and Y = @Y;