基于Date的SQL连接

时间:2016-08-10 14:50:48

标签: sql vertica

我有两张桌子: 表A

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

表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进行比较来更改。对于通过agrx_date更改brand_id后的月份,结果将反映新的brand_id。所有str_dates都是月度值。

最终结果如下:

+-------+----------+--------+
| 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或其他临时表。

2 个答案:

答案 0 :(得分:1)

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

范围将包括起点(>=),但最后是非包容性的(<)。您还需要处理开放范围的空案例。您可以在下面的联接中找到此逻辑。

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

答案 1 :(得分:0)

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

实施例

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

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