First, select DISTINCT to exclude duplicates from the result set, so you overload the condition. Adding the definition of βCβ and trying to put it into use makes it more confusing to follow. The data ultimately all comes from table "B", where it also has a key match in "A". Let's start with this ... And since you are not using anything from (B) Field_Y or (A) Field_X in your result set, do not add them to the mix of confusion.
SELECT DISTINCT B.ID, CASE WHEN B.Field_Z IN ('TEST_1','TEST_2') THEN 'CATEG_1' WHEN B.Field_Z IN ('TEST_3','TEST_4') THEN 'CATEG_2' WHEN B.Field_Z IN ('TEST_5','TEST_6') THEN 'CATEG_3' ELSE 'CATEG_4' END AS CATEG FROM B JOIN A ON B.ID = A.ID WHERE B.Field_Z IN ( 'TEST_1', 'TEST_2', 'TEST_3', 'TEST_4', 'TEST_5', 'TEST_6' )
The where clause will only include the qualification values ββof the category that you want, and still have results for each category.
Now, if you really need other values ββfrom your Field_Y or Field_X field, then this will create another request. However, your Tmp_C, Tmp_D and Tmp_E only request ID and CATEG columns.
DRapp source share