基于ID关联两表,筛选满足特定日期范围条件的记录
数据表匹配查询需求
现有数据表结构及数据
Table 1
| Loc_Id | Label_Id | Active_Date | Inactive_Date |
|---|---|---|---|
| 1 | 1001 | 2022/05/13 | 9999/12/31 |
| 2 | 1001 | 2018/05/20 | 2022/05/12 |
| 3 | 1001 | 2012/06/14 | 2018/05/12 |
Table 2
| Label_Id | Tab2_Active_Date | Tab2_Inactive_Date |
|---|---|---|
| 1001 | 2022/05/13 | 9999/12/31 |
| 1001 | 2018/05/22 | 2022/05/12 |
| 1001 | 2012/06/14 | 2018/05/12 |
查询需求
找出Table2中满足 Tab2_Active_Date > Table1.Active_Date 且 Tab2_Inactive_Date < Table1.Inactive_Date 的记录,同时关联对应Table1的Loc_Id。
示例:Table2中Tab2_Active_Date为2018/05/22的记录,大于Table1中Active_Date为2018/05/20的记录,符合条件。
限制条件
仅能通过Label_Id作为关联键连接两张表,不可使用日期关联,否则会导致数据不准确。
解决方案SQL
SELECT t1.Loc_Id, t2.Tab2_Active_Date, t2.Tab2_Inactive_Date FROM Table1 t1 JOIN Table2 t2 ON t1.Label_Id = t2.Label_Id WHERE t2.Tab2_Active_Date > t1.Active_Date AND t2.Tab2_Inactive_Date < t1.Inactive_Date;
预期输出
| Loc_Id | Tab2_Active_Date | Tab2_Inactive_Date |
|---|---|---|
| 2 | 2018/05/22 | 2022/05/12 |
内容的提问来源于stack exchange,提问作者Amit Verma
相关产品推荐
相关产品推荐

