如何解决如何根据特定的逻辑从两个表中联接并获取数据?
假设我有2张桌子,如下所示:
表1:
表2:
我想将2个表连接在一起,以便输出表具有“ 日期”列,表1中的“ hrs_billed_v1 ”列和“ hrs_billed_v2 ”列。有时,一个表中仅存在一个日期,而有时两个表中都存在一个日期。如果表1和表2中都存在日期,那么我想将表1中的 hrs_billed_v1 和表2中的 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的“ 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 ()
易于表达连接条件
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。