首页 > 解决方案 > 在一列中加入 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      ....       

任何人都可以帮忙吗?

标签: sqloraclejoin

解决方案


如果只有一个idtable2您可以使用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;

适用于多个匹配项的更通用解决方案table2exists

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 

推荐阅读