In My database I have a row with multiple Codes, EG:
ID,Code1,Code2,Code3,Code4
These codes reference a Procedure Name in another table EG:
Code1 = 'Procedure one'
Code2 = 'Procedure two'
ect.
I needed to convert this single row to show one line for every code, and corresponding procedure name EG:
ID,ProcedureName
1,'Procedure One'
1,'Procedure two'
2,'Procedure one'
To get this to work I'm using an outer join with an OR statement, not the most performance effective, but since the ProcedureName Table isn't that large, i'm not too fussed about overhead at the moment, more about getting it to work.
FROM Events EV
LEFT JOIN ProcedureName PN
ON (PN.CODE = Ev.Code1)
OR (PN.CODE = Ev.Code2)
OR (PN.CODE = Ev.Code3)
OR (PN.CODE = Ev.Code4)
This works, however Now I have the problem of being able to tell What procedure is the Primary, and Secondary. Usually the Primary/secondary is denoted purely by whatever one is in the first Code. IE the primary would be whatever is in Code1, secondary in code2, ect.
However since I have now Joined using an OR, i now have no idea what Code that the procedure has joined to.
I've thought of just doing a case statement
CASE
WHEN PN.CODE = Ev.Code1 THEN
'(Primary) ' + ISNULL(PN.NAME, '')
WHEN PN.CODE = Ev.Code2 THEN
'(Secondary) ' + ISNULL(PN.NAME, '')
WHEN PN.CODE = Ev.Code3 THEN
'(Tertiary) ' + ISNULL(PN.NAME, '')
WHEN PN.CODE = Ev.Code4 THEN
'(Quaternary) ' + ISNULL(PN.NAME, '')
END AS ProcedureName,
However this has the major issue of, on the off chance, that both code1 and code2 are the same code. Which means they will both show up as primary.
Can anyone give me any hints as to how to find out what the OR join actually Joined on? did it join on code1, code2? is there perhaps a better way to write the join that will allow me to have multiple lines per ID (depending on amount of codes) whilst still allowing me to find out where they are Code1 or code2?