具有复杂连接的sql查询
我有三个表:
- 第一个有三列(ID,类别,开始日期,结束日期)
- 第二个也有相同的三列(ID,类别,开始日期,结束日期)
- 第三个有三列(键,类别1,类别2) )
我创建了一个 sql 脚本,如果第二个表中的一行位于第一个表中为给定类别定义的时间段内(其中 table1.ID = table2.ID 且 table1.category = table2.category),则该脚本返回 1。
我现在想做的是创建一个 SQL 脚本,检查第二个表中的行是否在第一个表中为给定类别和 id 定义的时间段内,或者是否在 ID1_StartDate 和 ID2_EndDate 定义的时间段内(其中 ID1 和 ID2 是连续的,这意味着它们具有相同的类别,并且如果我们按日期升序排列,则该类别 id2 位于 id1 之后)(如果 table3 中这两个类别存在这样的关系)。
I have three tables :
- The first one has three columns(ID,Category,StartDate,EndDate)
- The second one has also the same three columns (ID,Category,StartDate,EndDate)
- The third one has three columns (Key,Category1,Category2)
I have created a sql script that returns 1 if a row from the second table is within the period defined in the first table for the given category (where table1.ID = table2.ID and table1.category = table2.category).
What I would like to do now is to create a SQL script that checks if a row from the second table is within the period defined in the first table for the given category and id, or if is within the period defined by ID1_StartDate and ID2_EndDate (Where ID1 and ID2 are successive, meaning that they have the same category and if we put in date ascending order this category id2 is after id1) if there is such a relationship in table3 for these two categories.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果满足以下任一条件,以下查询将返回 table1 ID:
1) 表 1 描述的日期范围与表 2 中的日期范围完全相交
2) 表 1 描述的日期范围与以 开头的日期范围相交table2 中行的开始日期,并以 table2 中按时间顺序排列的下一个具有相同类别的行的结束日期结束。
我不太明白这个场景中第三个表的用途,所以暂时忽略它。希望这仍然能让您更接近您正在寻找的答案。
The following query will return the table1 ID if either of these conditions are true:
1) the date range described by table 1 intersects at all with the date range in table2
2) the date range described by table 1 intersects with the date range beginning with the start date of a row in table2 and ending at the enddate of the next chronological row in table2 with the same category.
I don't entirely understand the use of the third table in this scenario, so it is ignored for the time being. Hopefully this will still get you closer to the answer you're looking for.