I have a status table A with Code & its description related to a particular name.
Code Desc Name
01 INITIAL STATUS_A
02 SUCCESS STATUS_A
03 FAILED STATUS_A
04 FAILED STATUS_B
05 RETRY STATUS_C
06 SUCESS STATUS_D
and so on... Now I have a table B as master record with code associate from Table A.
ID column1 column2 column3 statusA statusB statusC statusD
432 XXXX YYYY ZZZZ 03 04 05 06
Now I need to form a query to get output data with code description from table A.
I have done this using left outer join. Can someone suggest a better solution.
Left Outer Join Query
Select b.column1 ,b.column2, a1.Desc as Status_A_Desc , a2.Desc as Status_B_Desc, a3.Desc as Status_C_Desc, a4.Desc as Status_D_Desc from B b left outer join A a1 on a1.code = b.statusA and a1.Name ='STATUS_A' left outer join A a2 on a2.code = b.statusB and a2.Name ='STATUS_B' left outer join A a3 on a3.code = b.statusC and a3.Name ='STATUS_C' left outer join A a4 on a4.code = b.statusD and a4.Name ='STATUS_D' where b.ID = 432
You can use conditional aggregation instead:
select a.code,
max(case when a.name = 'Status_A' then a.desc end) as a,
max(case when a.name = 'Status_B' then a.desc end) as b,
max(case when a.name = 'Status_C' then a.desc end) as c,
max(case when a.name = 'Status_D' then a.desc end) as d
from a
group by a.code;
Depending on your database, the joins might be better. This has the advantage that you can add as many fields as you like with basically the same performance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.