2016-05-26 71 views
0

我確定這是在某個地方回答的,但我不太確定如何搜索它。SQL中一個表的多重聯接

我有一個表,[tbl_Data],看起來像這樣:

ID| From_Dt | To_Dt  | 
1 |01/01/2016 | 01/03/2016| 
1 |01/04/2016 | 01/09/2016| 
1 |01/09/2016 | 01/20/2016| 

希望輸出的樣子:

ID|Prev_From_Dt|Prev_To_Dt |Recent_From_Dt|Recent_To_Dt| 
1 |01/01/2016 |01/03/2016 |01/04/2016 |01/09/2016 | 
1 |01/04/2016 |01/09/2016 |01/09/2016 |01/20/2016 | 

這是我嘗試在代碼:

SELECT 
    t1.ID, 
    Prev_From_DT = t1.FROM_DT, 
    Prev_To_DT = t1.TO_DT, 
    Recent_From_DT = t2.FROM_DT, 
    Recent_To_DT = t2.TO_DT 
FROM 
    tbl_Data t1 
    LEFT JOIN tbl_Data t2 on t1.ID = t2.ID AND t1.TO_DT <= t2.FROM_DT 
+1

您正在使用哪個版本的SQL? (MySQL,Postgres等)如果它是MySQL,那麼你可能會發現這個SO回答有幫助http://stackoverflow.com/questions/1284441/how-does-a-mysql-self-join-work(魔術短語是「自我連接」 - 一個與自身連接的表格)。 –

+0

你用你試過的查詢得到了什麼輸出? –

+0

使用MSSQL。我提供的查詢爲每個小於To_Dt的From_Dt創建一條記錄。 – CurlieQ1034

回答

0

您可以計算rownumbers,然後在前一行中輸入join以獲取當前行和下一行的dat e在同一行上。

with rownums as (select *,row_number() over(partition by id order by from_dt) rn from t) 
select 
r1.id, 
r1.from_dt prev_from_dt,r1.to_dt prev_to_dt, 
r2.from_dt recent_from_dt,r2.to_dt recent_to_dt 
from rownums r1 
join rownums r2 on r1.rn = r2.rn-1 and r1.id=r2.id 

或者只是使用lead函數來獲取下一行的值。

select * from (
select id, 
from_dt prev_from_dt,to_dt prev_to_dt 
lead(from_dt) over(partition by id order by from_dt) recent_from_dt, 
lead(to_dt) over(partition by id order by from_dt) recent_to_dt 
from t) x 
where recent_from_dt is not null and recent_to_dt is not null