SQL合并条目,带有开始日期和最终日期的条目
我有两个表,我们称它们为A和B。表A有有关特定事件的数据,并且具有event_date
和Person
的唯一键列配对。表B随着时间的推移具有汇总数据,因此具有键列start_date
,end_date
和person
。对于给定的人来说,表B中的日期范围永远不会重叠,因此end_date
对于复合密钥而言并不是必需的。
以下是两个示例
SELECT event_date, person
FROM A
event_date | 人 |
---|---|
2021-10-01 | 爱丽丝 |
2021-101-01 | 鲍勃 |
2021-10-05 | 鲍勃 |
2021-11-05 | bob |
SELECT start_date, end_date, person, attribute
FROM B
start_date | end end end_date end_date | 人 | 属性 |
---|---|---|---|
2021-10-01 2021-01 | 2021-11-11-01 | Alice | Attribute 1 2021-10 Alice Attribute 1 |
2021-10 -01 | 2021-11-01 | BOB | 属性1 |
2021-11-01 | 2021-12-01 | BOB | 属性2 |
我想将属性
列添加到表A。合并应考虑到哪个日期范围event_date
列属于并选择适当的属性。合并后的最后一个表格应该像这样:
人 | 属性 | 2021-10-01 |
---|---|---|
爱丽丝 | 属性 | 1 |
2021-10-01 | 鲍勃 | 属性1 |
2021-105 | bob | attribute 1 |
2021-11-11-05 | bob | attribute 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_date | person |
---|---|
2021-10-01 | Alice |
2021-10-01 | Bob |
2021-10-05 | Bob |
2021-11-05 | Bob |
SELECT start_date, end_date, person, attribute
FROM B
start_date | end_date | person | attribute |
---|---|---|---|
2021-10-01 | 2021-11-01 | Alice | Attribute 1 |
2021-10-01 | 2021-11-01 | Bob | Attribute 1 |
2021-11-01 | 2021-12-01 | Bob | Attribute 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_date | person | attribute |
---|---|---|
2021-10-01 | Alice | Attribute 1 |
2021-10-01 | Bob | Attribute 1 |
2021-10-05 | Bob | Attribute 1 |
2021-11-05 | Bob | Attribute 2 |
How would one go about solving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在
BETWEEN
日期之前JOIN
。You can try to
JOIN
byBETWEEN
dates.