如何根据特定的逻辑从两个表中联接并获取数据?

问题描述

假设我有2张桌子,如下所示:

表1:

enter image description here

表2:

enter image description here

我想将2个表连接在一起,以便输出表具有“ 日期”列,表1中的“ hrs_billed_v1 ”列和“ hrs_billed_v2 ”列。有时,一个表中仅存在一个日期,而有时两个表中都存在一个日期。如果表1和表2中都存在日期,那么我想将表1中的 hrs_billed_v1 和表2中的 hrs_billed_v2 分配给输出表。

因此理想的结果将如下所示:

enter image description here

我尝试了“ FULL OUTPUT JOIN”,但是它在输出表中返回了一些“ date”的空值。以下是我编写的查询:

SELECT 
DISTINCT CASE WHEN table1.date is null then table2.date WHEN table2.date is null then table1.date end as date,CASE WHEN table1.hrs_billed_v1 is null then 0 else table1.hrs_billed_v1 END AS hrs_billed_v1,CASE WHEN table2.hrs_billed_v2 is null then 0 else table2.hrs_billed_v2 END AS hrs_billed_v2
FROM table1         
FULL OUTER JOIN table2 ON table1.common = table2.common

请注意,我用来连接table1和table2的“ common”列只是两个表中都存在的常量字符串。

任何建议将不胜感激!

解决方法

full join确实是您想要的。我认为应该是:

select 
    common,date,coalesce(t1.hrs_billed_v1,0) as hrs_billed_v1,coalesce(t2.hrs_billed_v2,0) as hrs_billed_v2
from table1 t1
full join table2 t2 using (common,date)

理论上:

  • 您没有显示common是什么;您的数据表明您要匹配同一日期的行-因此我将两者都置于联接条件中;您可能需要修改

  • 实际上应该不需要distinct

  • coalesce()case表达式短

  • 当两个表中要匹配的列具有相同的名称时,
  • using ()易于表达连接条件

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...