sql - 在一列中加入 2 个带有分类标签的表
问题描述
我在 Oracle 中有一个 SQL 表。我必须加入 2 个表(一个带有 ID 和其他数据,第二个带有 ID 和每行中的日期,第二个表显示在下面)但不想从第二个表中获取连接数据,而只需要标签(根据条件为 1 或 0该搜索 ID 的日期介于 21/08/01 到 21/08/31 之间)。
Table 2
# ID Date
# 1 21/08/01
# 2 21/07/02
# 3 21/08/24
# 4 21/08/02
# 5 21/06/03
# 6 21/08/05
# 7 21/08/26
# 8 21/08/05
我想要的输出应该如下所示:
Table 1
# ID Date Other data
# 1 1 ....
# 2 0 ....
# 3 1 ....
# 4 1 ....
# 5 0 ....
# 6 1 ....
# 7 1 ....
# 8 1 ....
任何人都可以帮忙吗?
解决方案
如果只有一个id
,table2
您可以使用left join
:
select t`.*,
(case when t2.date is null then 0 else 1 end) as flag
from table1 t1 left join
table2 t2
on t2.id = t1.id and
t2.date between date '2021-08-01' and date '2021-08-31;
适用于多个匹配项的更通用解决方案table2
是exists
:
select t.*,
(case when exists (select 1
from table2 t2
where t2.id = t1.id and
t2.date between date '2021-08-01' and date '2021-08-31'
)
then 1 else 0
end) as flag
from table1 t1
推荐阅读
- powerbi - 为两个日期之间的行计算不同表中的值的总和
- javascript - javascript/typescript 的单元测试
- swift - 我如何在 Objective-C 中编写这个方法 - (应用程序:继续 userActivity:restoreHandler :)?
- shell - 为什么像 [ $var == 'str' ] 这样的 zsh 代码作为命令运行良好,但作为脚本文件出错?
- javascript - 创建一个跨越两个导航栏的元素
- javascript - javascript到plc串口modbus rtu问题
- angular - 如何检查 transloco 中缺少的翻译键?
- jenkins - 分析声纳扫描仪时出现 Jenkins 错误
- java - 如何在java中获取文件夹大小
- jquery - Plupload - 按 mime 类型限制文件类型