2016-05-23 34 views
-1

下面是來自不同表格的數據。將來自不同表格的數據合併到日期範圍之間的一個表中SQL Server

ID  StudentID Tablename StartDate enddate 
8849 2   Service  11/4/2010 11/2/2011 
8850 2   Service  11/4/2010 11/2/2011 
16512 2   Placement 11/4/2010 6/30/2011 
16513 2   Placement 09/01/2011 11/02/2011 

我想輸出象下面這樣:

SE_ID ST_ID PL_ID StartDate enddate 
8849 2  16512 11/04/2010 06/30/2011 
8849 2  16513 09/01/2011 11/02/2011 
8850 2  16512 11/04/2010 06/30/2011 
8850 2  16513 09/01/2011 11/02/2011 

我曾嘗試下面的SQL。我得到正確的結果,但查詢需要很長時間。有沒有其他方式可以達到不使用左外連接的相同結果?

with 
Daterange as 
( 
select SE_ID,se_st_id as ST_ID,'Service' AS Tablename, SE_StartDate AS StartDate ,se_enddate as enddate from spipublic.service 
union 
select PL_ID,pl_st_id as ST_ID,'Placement' AS Tablename, PL_StartDate AS StartDate,pl_enddate as enddate from spipublic.placement 
union 
select SU_ID,su_st_id as ST_ID,'StudentStatus' AS Tablename,SU_StartDate AS StartDate,SU_EndDate as enddate from spipublic.studentstatus 
) 
select Distinct  
     D.ST_ID 
     ,SU.SU_ID 
     , PL.PL_ID 
    , SE.SE_ID 
    ,D.startdate 
    ,D.EndDate 
from spipublic.studentstatus SU 
inner join Daterange D 
on SU.SU_ST_ID=D.ST_ID and (SU.SU_EndDate IS NULL OR SU.SU_ENDDate>D.Startdate) and SU.SU_STartDate<D.EndDate 
left join spipublic.service SE 
on SE.SE_ST_ID=D.ST_ID and (SE.SE_ENDDate IS NULL OR SE.SE_ENDDATE>D.StartDate) and SE.SE_StartDate<D.EndDate 
left join spipublic.placement PL 
on PL.PL_ST_ID=D.ST_ID and (PL.PL_EndDate IS NULL OR PL.PL_EndDate>D.StartDate) and PL.PL_StartDate<D.EndDate 
where D.st_id=2 
+0

我不明白你的數據表1和數據表2之間的關係。你能用文字描述你想要達到的目標嗎? –

+0

這裏沒有足夠的信息給任何人提供任何真正的幫助。我們不知道你的表,索引,數據是什麼樣的。如果沒有這些細節,我們無法提供幫助。這將是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

+0

表2是我試圖實現的輸出。基本上,我想在同一個表中將學生的所有數據(如登記,安置,服務)在相同的日期範圍內結合起來 – GPK

回答

1

從給出的例子中很難說,但是離開我的頭頂,UNION ALL可能會加快速度。

+0

第一張圖表是來自展示位置,服務和註冊表的所有聯盟的結果。如何在結果集之後彙總數據? – GPK

相關問題