I have a table of 2 columns like below. One ID
can have multiple Code
.
╔═════════╗
║ ID Code ║
╠═════════╣
║ 1 0 ║
║ 1 16 ║
║ 1 41 ║
║ 2 1 ║
║ 2 40 ║
║ 3 41 ║
║ 3 67 ║
║ 4 70 ║
║ 5 16 ║
║ 5 67 ║
║ 6 41 ║
║ 6 68 ║
╚═════════╝
My desired outcome is identifying each ID
belongs to which Group
, by checking all Code
of that ID
. The checking rule is:
╔══════════════════════════════════╦═══════╗
║ Code ║ Group ║
╠══════════════════════════════════╬═══════╣
║ Contains 0 ║ M1 ║
║ Contains 1 or 16 or 40 ║ M2 ║
║ Contains 41 or 67 ║ M3 ║
║ Contains 68 or 70 ║ M4 ║
║ Contains codes of both M2 and M3 ║ M5 ║
║ Contains codes of both M3 and M4 ║ M6 ║
╚══════════════════════════════════╩═══════╝
Note: If ID
has Code
0, Group
is M1, then stop checking other rules.
The required output should looks like this:
╔══════════╗
║ ID Group ║
╠══════════╣
║ 1 M1 ║
║ 2 M2 ║
║ 3 M3 ║
║ 4 M4 ║
║ 5 M5 ║
║ 6 M6 ║
╚══════════╝
What I have tried so far is using STUFF
and FOR XML PATH
studied from this thread:
SELECT *,
STUFF((SELECT DISTINCT ', ' + Code FROM tblFee WHERE ID = t.ID FOR XML PATH ('')), 1, 1, '') AS Group
FROM (
SELECT DISTINCT ID FROM tblFee
) t
to have the result likes:
╔══════╦═══════════╗
║ Code ║ Group ║
╠══════╬═══════════╣
║ 1 ║ 0, 16, 41 ║
║ 2 ║ 1, 40 ║
║ 3 ║ 41, 67 ║
║ 4 ║ 70 ║
║ 5 ║ 16, 67 ║
║ 6 ║ 41, 48 ║
╚══════╩═══════════╝
then use CASE...WHEN...
and LIKE
to check the rule. However my production data contains nearly 1 million records, so performance is a big problem.