SQL - 如果无法匹配,则使用默认值加入

时间:2017-08-14 15:07:22

标签: sql db2

我有两个看起来像这样的表:

表1:

+---------+---------+-------------+
| Activity| Area    | Responsible |
+---------+---------+-------------+
| Cooking | Meat    |   Peter     |
| Cooking | Vegan   |   Sia       |
| Cleaning| Kitchen |   Paul      |
| Cleaning| Toilets |   Selina    |
+---------+---------+-------------+

表2:

+---------+---------+-------------+
| Activity| Area    | Day         |
+---------+---------+-------------+
| Cooking | Meat    |   Monday    |
| Cooking | Vegan   |   Monday    |
| Cleaning| Garden  |   Friday    |
| Cleaning| Toilets |   Friday    |
+---------+---------+-------------+

现在我想要一个SQL加入它们,这样我每天都可以看到负责人。

我认为标准SQL看起来像这样:

SELECT DAY, ACTIVITY, RESPONSIBLE 
FROM TABLE_2 2
LEFT JOIN TABLE_1 1 
ON 1.ACTIVITY = 2.ACTIVITY AND 1.AREA = 2.AREA

但现在有些行不能联合(例如清洁花园)。 在那种情况下(如果无法加入),我希望Peter始终对此负责。

我可以在一次加入中做到这一点(可能是CASE声明?)或者你会怎么做?

1 个答案:

答案 0 :(得分:2)

不要使用数字作为表名,即使DB2允许也是如此。数字应该是数字。

您正在寻找COALESCE()

SELECT t2.DAY, t2.ACTIVITY, COALESCE(t1.RESPONSIBLE, 'Peter') as Responsible 
FROM TABLE_2 t2 LEFT JOIN
     TABLE_1 t1 
     ON t1.ACTIVITY = t2.ACTIVITY AND t1.AREA = t2.AREA;