将来自不同表的数据组合到日期范围SQL Server之间的一个表中

时间:2016-05-23 16:31:05

标签: sql sql-server database sql-server-2008

以下是来自不同表格的数据。

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

1 个答案:

答案 0 :(得分:1)

从给出的例子中很难说,但是在我的脑海中,UNION ALL可能会加速它。