SQL合并条目,带有开始日期和最终日期的条目

发布于 2025-01-19 04:44:03 字数 1632 浏览 0 评论 0原文

我有两个表,我们称它们为A和B。表A有有关特定事件的数据,并且具有event_datePerson的唯一键列配对。表B随着时间的推移具有汇总数据,因此具有键列start_dateend_dateperson。对于给定的人来说,表B中的日期范围永远不会重叠,因此end_date对于复合密钥而言并不是必需的。

以下是两个示例

SELECT event_date, person
FROM A
event_date
2021-10-01爱丽丝
2021-101-01鲍勃
2021-10-05鲍勃
2021-11-05bob
SELECT start_date, end_date, person, attribute
FROM B
start_dateend end end_date end_date属性
2021-10-01 2021-012021-11-11-01AliceAttribute 1 2021-10 Alice Attribute 1
2021-10 -012021-11-01BOB属性1
2021-11-012021-12-01BOB属性2

我想将属性列添加到表A。合并应考虑到哪个日期范围event_date列属于并选择适当的属性。合并后的最后一个表格应该像这样:

属性2021-10-01
爱丽丝属性1
2021-10-01鲍勃属性1
2021-105bobattribute 1
2021-11-11-05bobattribute 2

event_date 关于解决这个问题?

I have two tables, lets call them A and B. Table A has data regarding specific events and has a unique key column pairing of event_date and person. Table B has aggregate data over time and thus has key columns start_date,end_date and person. The date ranges in table B will never overlap for a given person so end_date is not strictly necessary for the composite key.

Below are two examples

SELECT event_date, person
FROM A
event_dateperson
2021-10-01Alice
2021-10-01Bob
2021-10-05Bob
2021-11-05Bob
SELECT start_date, end_date, person, attribute
FROM B
start_dateend_datepersonattribute
2021-10-012021-11-01AliceAttribute 1
2021-10-012021-11-01BobAttribute 1
2021-11-012021-12-01BobAttribute 2

I would like to add the attribute column to table A. The merger should consider in which date range the event_date column falls into and choose the appropriate attribute. The final table after the merge should look like this:

event_datepersonattribute
2021-10-01AliceAttribute 1
2021-10-01BobAttribute 1
2021-10-05BobAttribute 1
2021-11-05BobAttribute 2

How would one go about solving this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够爱げ你 2025-01-26 04:44:03

您可以尝试在 BETWEEN 日期之前JOIN

SELECT a.*,b.attribute
FROM A a
JOIN B b
ON a.event_date BETWEEN b.start_date AND b.end_date
AND a.person = b.person

You can try to JOIN by BETWEEN dates.

SELECT a.*,b.attribute
FROM A a
JOIN B b
ON a.event_date BETWEEN b.start_date AND b.end_date
AND a.person = b.person
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文