首页 > 解决方案 > 如何根据特定逻辑从任一表中加入和获取数据?

问题描述

假设我有 2 个表,如下所示:

表格1:

在此处输入图像描述

表 2:

在此处输入图像描述

我想将 2 个表连接在一起,以便输出表将有一个“日期”列、一个来自 table1 的“hrs_billed_v1”列和一个来自table2的“ hrs_billed_v2 ”列。有时一个日期只存在于其中一个表中,有时一个日期存在于两个表中。如果 table1 和 table2 中都存在日期,那么我想将table1中的hrs_billed_v1和 table2 中的hrs_billed_v2分配到输出表。

所以理想的结果应该是这样的:

在此处输入图像描述

我试过“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 的“公共”列只是两个表中都存在的常量字符串。

任何建议将不胜感激!

标签: sqlpostgresqlfull-outer-joinsql-null

解决方案


Afull 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 ()当要匹配的列在两个表中具有相同名称时,可以方便地表达连接条件


推荐阅读