简体   繁体   中英

Use of coalesce function in SQL Query

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:

  • If the value of CHA is not present in Material_Code column of material_Details table then I need to search for the value of REZ in Material_Code column of Material_Details table.
  • If both are not found i need to display it as blank.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM