【问题标题】:combine data from different tables into one table between date ranges SQL Server将不同表中的数据合并到一个日期范围之间的表中 SQL Server
【发布时间】:2016-05-23 16:31:04
【问题描述】:

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

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 和数据表 2 之间的关系。你能用文字描述你想要达到的目标吗?
  • 这里没有足够的信息供任何人提供任何真正的帮助。我们不知道您的表、索引、数据是什么样的。如果没有这些细节,我们将无法提高性能。这将是一个很好的起点。 spaghettidba.com/2015/04/24/…
  • 表 2 是我想要实现的输出。基本上,我想将同一日期范围内学生的所有数据(如入学、安置、服务)合并到一张表中
  • where st_id=2 添加到联合中的每个选择语句中。现在你正在将大量数据注入内存并选择一个非常小的数据集。
  • 我需要为所有学生运行查询。我做了 st_id=2 只为一名学生获得上述结果。

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


【解决方案1】:

从给出的例子中很难说,但我不知道 UNION ALL 可能会加快速度。

【讨论】:

  • 第一个图表是结合所有来自安置表、服务表和入学表的结果。如何在该结果集之后聚合数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多