简体   繁体   English

如果在两个不同的表中没有匹配项,则SQL查询返回列的默认值

[英]SQL query to return default value for a column if no Match in two different tables

I need to create an output table matching two tables. 我需要创建一个匹配两个表的输出表。 If the second table does not match with the first table then return a default value for a column. 如果第二个表与第一个表不匹配,则返回列的默认值。

Example- 例-

Table 1 - 表格1 -

|---------------------|------------------|
|          Id         |        Name      |
|---------------------|------------------|
|          1          |        Jon       |
|---------------------|------------------|
|          2          |        Dan       |
|---------------------|------------------|
|          3          |        Mark      |
|---------------------|------------------|
|          4          |      Phillips    |
|---------------------|------------------|
|          5          |       Watson     |
|---------------------|------------------|

Table 2 - 表2-

|---------------------|------------------|
|          Name       |      Result      |
|---------------------|------------------|
|          Jon        |       Pass       |
|---------------------|------------------|
|        Phillips     |       Pass       |
|---------------------|------------------|
|         Watson      |       Fail       |
|---------------------|------------------|

Final Output Table with Join and if data does not match in second table then assign a default value "Fail" to it - 带有连接的最终输出表,如果第二个表中的数据不匹配,则为其分配默认值“失败”-

|---------------------|------------------|------------------|
|          Id         |        Name      |      Result      |
|---------------------|------------------|------------------|
|          1          |        Jon       |       Pass       |
|---------------------|------------------|------------------|
|          2          |        Dan       |       Fail       |
|---------------------|------------------|------------------|
|          3          |        Mark      |       Fail       |
|---------------------|------------------|------------------|
|          4          |      Phillips    |       Pass       |
|---------------------|------------------|------------------|
|          5          |       Watson     |       Fail       |
|---------------------|------------------|------------------|

How can this be achieved in SQL. 如何在SQL中实现。

Left join table1 with table2 and use coalesce to replace NULL values (when right table has no match) with the default value: 左连接table1和table2并使用coalesce用默认值替换NULL值(当右表不匹配时):

select t1.id, 
       t1.name, 
       coalesce(t2.result, 'fail') as Result      
from Table_1 as t1
left outer join Table_2 as t2 on t1.name = t2.name

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

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