sql - 如何根据特定逻辑从任一表中加入和获取数据?
问题描述
假设我有 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 的“公共”列只是两个表中都存在的常量字符串。
任何建议将不胜感激!
解决方案
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 ()
当要匹配的列在两个表中具有相同名称时,可以方便地表达连接条件
推荐阅读
- roslyn-code-analysis - 您可以从分析器中获取当前项目吗?
- go - 如何为 []map[string]string 添加示例
- oracle - 我想让它加起来 ABC 的值
- java - 使用 IntelliJ-IDEA 的应用程序启动方法中的异常
- c# - 表单应用程序不会接受我的 SQL 表列和用户名,但它会接受密码
- c++ - Boost Transform 产生 Inf 返回值
- excel - 使用 Excel-VBA 创建字符串/文本和图像并将其插入 Word 文档表格单元格
- excel - 以任意顺序匹配 2 个或多个条件的返回值
- dart - 在颤动中创建水平滚动的 3 行列
- ruby-on-rails-5 - 并行 has_man 通过