Postgres视图中的变量?

2024-04-23 12:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Postgres中有一个视图,它查询一个主表(1.5亿行)并检索前一天的数据(一个返回SELECT的函数;这是获得视图以遵守分区约束的唯一方法),然后将其与二维表连接起来。这很好,但是如何在Python中循环查询呢?有没有办法让约会充满活力?你知道吗

for date in date_range('2016-06-01', '2017-07-31'):
    (query from the view, replacing the date with the date in the loop)

我的解决方法是将整个视图复制并粘贴为一个巨大的select语句格式字符串,然后在循环中传递日期。这是可行的,但似乎必须有一个更好的解决方案来利用现有的视图或传入一个将来可能有用的变量。你知道吗


Tags: the数据方法函数in视图fordate
1条回答
网友
1楼 · 发布于 2024-04-23 12:17:45

要在for循环的间隔内逐日循环,可以执行以下操作:

import datetime

initialDate = datetime.datetime(2016, 6, 1)
finalDate = datetime.datetime(2017, 7, 31)

for day in range((finalDate - initialDate).days + 1):
    current = (initialDate + datetime.timedelta(days = day)).date()
    print("query from the view, replacing the date with " + current.strftime('%m/%d/%Y'))

将打印替换为对查询的调用。如果日期是字符串,则可以执行以下操作:

initialDate = datetime.datetime.strptime("06/01/2016", '%m/%d/%Y')

相关问题 更多 >