2016-08-10 98 views
1

我有兩個表: 表ASQL JOIN基於日期

+-------+----------+ 
| 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。在brand_id通過agrx_date更改後的月份,結果會反映出新的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或其他臨時表。

+1

請提供您用於生成發佈結果的詳細邏輯。 –

+0

請讓我知道你在這裏比較日期 – robinbansalsolutions

+0

我編輯了這個問題。 – Bernardo

回答

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 
+0

奇妙的,那有效。謝謝! – Bernardo

0

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

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

,或者你想使用的任何領域和格式。