I want to combine the following tables with the logic given below using sql select statement:
Table: Plant
ID | identifier | code |
---|---|---|
cbf2 | 5200 | consistent |
b3aa | 5201 | consistent |
Table: Supplier
ID | identifier | code |
---|---|---|
3527 | SD501 | consistent |
Table: Material
ID | identifier | code | PC_ID | wxyz_Code |
---|---|---|---|---|
b4a1 | B50003 | consistent | a | 1 |
97bb | B50004 | consistent | b | 1 |
e189 | B50005 | consistent | c | 0 |
- Derived table's formattedID column is a combination of identifier columns present in the Plants, Material, Supplier table.
- Only rows from the Material table will be considered where column wxyz_Code is = 1.
- wxyz_Code in Material table is renamed as abcd_Code in the DerivedTable table.
- Material_ID, Plant_ID, Supplier_ID columns in DerivedTable are populated from the ID column of Material, Plant, Supplier, respectively.
- PC_ID in DerivedTable is filled from Material's PC_ID column
Resulting Table: DerivedTable
ID | formattedID | abcd_Code | Material_ID | Supplier_ID | Plant_ID | PC_ID |
---|---|---|---|---|---|---|
Automatically Generated | B50003/5201 | 1 | b4a1 | 'null' | cbf2 | a |
Automatically Generated | B50003/5200 | 1 | b4a1 | 'null' | b3aa | a |
Automatically Generated | B50003/5201/SD501 | 1 | b4a1 | 3527 | cbf2 | a |
Automatically Generated | B50003/5200/SD501 | 1 | b4a1 | 3527 | b3aa | a |
Automatically Generated | B50004/5201 | 1 | 97bb | 'null' | cbf2 | b |
Automatically Generated | B50004/5202 | 1 | 97bb | 'null' | b3aa | b |
Automatically Generated | B50004/5201/SD501 | 1 | 97bb | 3527 | cbf2 | b |
Automatically Generated | B50004/5200/SD501 | 1 | 97bb | 3527 | b3aa | b |
CodePudding user response:
While this code is for postgreSQL, would apply to many SQL backends with slight change (ie: || with ):
select 'Automatically Generated' as Id,
m.identifier || '/' || p.identifier as formattedId,
m.wxyz_code as abcd_code,
m.id as Material_Id,
null as Supplier_Id,
p.Id as Plant_id,
m.pc_id
from Plant p,
Material m
where m.wxyz_code = 1
union all
select 'Automatically Generated' as Id,
m.identifier || '/' || p.identifier || '/' || s.Identifier as formattedId,
m.wxyz_code as abcd_code,
m.id as Material_Id,
s.id as Supplier_Id,
p.Id as Plant_id,
m.pc_id
from Plant p,
Supplier s,
Material m
where m.wxyz_code = 1
order by formattedId;