SQL 根据日期加入

SQL join based on Date

我有两个表: Table一个

+-------+----------+
| prop  | str_date |
+-------+----------+
| AL408 | 3/1/2009 |
| AL408 | 4/1/2009 |
| AL408 | 5/1/2009 |
| AL408 | 6/1/2009 |
+-------+----------+

Table B

+---------+-----------+----------+
| prop_id | agrx_date | brand_id |
+---------+-----------+----------+
| AL408   | 5/5/1986  | CI       |
| AL408   | 6/30/1994 | CI       |
| AL408   | 5/3/1999  | CI       |
| AL408   | 4/21/2006 | CI       |
| AL408   | 3/20/2009 | QI       |
+---------+-----------+----------+

我想将 brand_id 拉入我的结果查询,但 brand_id 通过比较 str_date 与 agrx_date 相应地发生变化。 brand_id 通过 agrx_date 更改后的一个月,结果将反映新的 brand_id。所有 str_date 都是月度值。

最终结果如下所示:

+-------+----------+--------+
| prop  | str_date | Result |
+-------+----------+--------+
| AL408 | 3/1/2009 | CI     |
| AL408 | 4/1/2009 | QI     |
| AL408 | 5/1/2009 | QI     |
| AL408 | 6/1/2009 | QI     |
+-------+----------+--------+

这是我目前所知道的(不正确),但我不确定如何获得最终结果。

select
a.prop
,a.str_date
,b.agrx_date
,b.brand_id

from tableA a
left join tableB b
on a.prop = b.prop_id
and a.str_date < b.agrx_date

where a.prop = 'AL408'

我通过 Tableau 传递它,所以我不能使用 CTE 或其他临时表。

您可以使用 DATE_FORMAT 更改日期以匹配格式。

例子

DATE_FORMAT(str_date,'%m-%d-%Y') 

或您要使用的任何字段和格式。

您可以使用 lead() 分析函数创建日期范围。然后可以将日期范围用作 theta 连接的一部分以引入正确的品牌。这是从下一条记录中提取日期值的非常简单的方法,请参阅下面 next_agrx_date 的定义。

该范围将包括开始 (>=),但不包括结束 (<)。您还需要处理开放式范围的 null 情况。您可以在下面的连接中找到此逻辑。

select
   a.prop
  ,a.str_date
  ,b.agrx_date
  ,b.brand_id
from tableA a 
left join
( select 
     prop
    ,agrx_date
    ,brand_id
    ,lead(agrx_date) over (partition by prop order by agrx_date) next_agrx_date 
  from tableB ) b 
on (b.prop = a.prop and a.str_date >= b.agrx_date and (a.str_date < b.next_agrx_date or b.next_agrx_date is null))
order by prop, str_date