I have a specific requirement where i have two tables as mentioned below: Material Details
and Specification Details
. What i have to do is split the Sp_Code
column value using "-"(hyphen). And then find the Material_Value
of the Sp_Code
in Material_Details
table.
For example:
If I split "CHA-REZ" using "-" then I have two values, "CHA" and "REZ". Now I have to find the Material_Value for CHA in Material_Details table:
Please find the below table for reference. Any help will be appreciated.
Material_Details Specification_Details
Material_Code Material_Value Sp_Code Value
ABC Ammeter CHA-REZ 1
TAB Table PAP-CHA 2
CHA Chair TAB-BBV 3
PAP Paper CNN-ASD 4
Use a subquery to derive the 'foreign keys', then LEFT JOIN
the Material_Detail
table on to the subquery twice and COALESCE
the columns required from the Material_Detail
tables
SELECT *, COALESCE(md1.Material_Value, md2.Material_Value, '') Material_Value
FROM (
SELECT *,
SUBSTRING(Sp_Code, 1, CHARINDEX('-', Sp_Code, 1)-1) FK1,
SUBSTRING(Sp_Code, CHARINDEX('-', Sp_Code, 1)+1, LEN(Sp_Code)-1) FK2
FROM Specification_Details
) spec
LEFT JOIN Material_Details md1 ON spec.FK1 = md1.Material_Code
LEFT JOIN Material_Details md2 ON spec.FK2 = md2.Material_Code
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.