简体   繁体   English

在SQL查询中使用合并功能

[英]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 . 我有一个特殊要求,其中有两个如下所述的表格: Material DetailsSpecification Details What i have to do is split the Sp_Code column value using "-"(hyphen). 我要做的是使用“-”(连字符)拆分Sp_Code列值。 And then find the Material_Value of the Sp_Code in Material_Details table. 然后找到Material_Value中的Sp_CodeMaterial_Details表。

For example: 例如:

If I split "CHA-REZ" using "-" then I have two values, "CHA" and "REZ". 如果我使用“-”分割“ CHA-REZ”,则我有两个值,“ CHA”和“ REZ”。 Now I have to find the Material_Value for CHA in Material_Details table: 现在,我必须在Material_Details表中找到CHA的Material_Value:

  • 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. 如果CHA的值不在material_Details表的Material_Code列中,那么我需要在Material_Details表的Material_Code列中搜索REZ的值。
  • 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 使用子查询派生“外键”,然后两次将Material_DetailLEFT JOIN到子查询上,并从Material_Detail表中COALESCE所需的列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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