如何从当前和历史记录中创建时间表?
假设我有一个看起来像这样的当前表:
location status price
A sold 3
并且我有一个看起来这样的历史表:
location field oldval_str newval_str oldvar_num newval_num created_at
A status closed sold null null 2022-06-01
A status listed closed null null 2022-05-01
A status null listed null null 2022-04-01
A price null null null 1 2022-04-01
A price null null 1 2 2022-05-01
A price null null 2 3 2022-06-01
如何在纯SQL中构建一个诸如以下内容的时间表?
location status price created_at
A listed 1 2022-04-01
A closed 2 2022-05-01
A sold 3 2022-06-01
我正在使用postgresdb是方言帮助!
我知道我可以在Python中这样做,我坚持使用历史记录的字段动态命名列。想找到一个所有SQL解决方案。有任何资源要指向吗?
Let's say I have a current table that looks like this:
location status price
A sold 3
and I have a history table that looks as such:
location field oldval_str newval_str oldvar_num newval_num created_at
A status closed sold null null 2022-06-01
A status listed closed null null 2022-05-01
A status null listed null null 2022-04-01
A price null null null 1 2022-04-01
A price null null 1 2 2022-05-01
A price null null 2 3 2022-06-01
How can I build a temporal table such as the following in pure SQL?
location status price created_at
A listed 1 2022-04-01
A closed 2 2022-05-01
A sold 3 2022-06-01
I am using a PostgresDB is dialect helps!
I know I can do this in Python, I'm stuck on calling dynamically named columns using the field from history. Would like to find an all SQL solution. Any resources to point to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用这样的查询
,请检查
0cefca4bf2c42e620efca0aCC0777154D位置表与
历史
表连接在一起,以获取所有可用的位置
行,即使是从未更改的值和历史记录
表不包含周围的任何行。如果您不需要它,只需单独使用
历史
表即可。You can use a query like this
Please, check a demo
Here the
locations
table is joined with thehistory
table to get all of the availablelocation
rows, even those which values was not ever changed, and thehistory
table does not contain any row about them.If you do not need it, just use the
history
table alone.