[英]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 Details
和Specification 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_Code
在Material_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:
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_Detail
表LEFT 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.