python - Python:将日期列表传递给 PostgreSQL 查询并循环 n 次
问题描述
嗨,我使用的是 PostgreSQL 12,并且有一个由几个 CTE 组成的 INSERT sql 语句,如下所示:
WITH CTE1 as (
select date, count(*) from customers where date = %(date_list)s group by date
),
CTE2 as (
select date, count(*) from customers where account_deleted is NULL and date = %(date_list)s group by date
)
INSERT INTO customers_final (date, customers)
select * from CTE1
union all
select * from CTE2
我现在想使用 Python 循环遍历不同客户数据集的日期列表(随着时间的推移,客户的不同快照)并多次运行上述查询,针对与我列表中不同日期对应的每个客户数据集运行一次。
Example of list: ('2021-03-21', '2021-03-22', '2021-03-23', etc).
预期结果应该是每个数据集每个日期一行(一个 CTE)。由于我们在示例中有 2 个 CTE,我们应该期望每个数据集每个日期有 2 行。
下面应该适用于单个数据集。不知道如何还遍历不同的表(客户表):
def insert_data(date_list: list):
sql_query = """WITH CTE1 as (
select date, count(*) from customers where date = %(date_list)s group by date
),
CTE2 as (
select date, count(*) from customers where account_deleted is NULL and date = %(date_list)s group by date
)
INSERT INTO customers_final (date, customers)
select * from CTE1
union all
select * from CTE2""" (
for date in date_list:
if date_list is not None and len(date_list) > 0:
params = {"date": date}
cursor.execute(sql_query, {"date": date})
else:
log.warning(f'No records found.')
if __name__ == '__main__':
date_list = ['2021-03-29', '2021-03-28', '2021-03-27', '2021-03-26']
insert_data(date_list)
解决方案
推荐阅读
- tkinter - 为什么 tkinter 框架与使用网格方法的 Tk 窗口大小不同?
- c - 如何对包含多个字符串的结构应用基数排序(使用计数排序)
- apache - 只允许从它们所在的网站访问目录中的文件
- selenium - selenium 与 javascript 的 firefox 关闭选项卡,但 SetTimeout() 不正常
- java - 如何在不重新加载页面的情况下提交表单
- node.js - 如何使用 Node 从远程服务器获取数据
- javascript - 用python和react js创建一个electron JS桌面应用
- upgrade - 从 Artifactory 2.3.3.1 升级
- docker - 无法使用撰写文件版本 2.4 部署 docker 堆栈
- perl - Perl:表达式优先级和评估