在 sqlalchemy 中实现窗口函数时需要帮助
Posted
技术标签:
【中文标题】在 sqlalchemy 中实现窗口函数时需要帮助【英文标题】:Need help in implementing a window function in sqlalchemy 【发布时间】:2021-09-24 01:01:56 【问题描述】:我正在尝试实现这个窗口功能:
-
它按portfolio_id 分组。
在每个组中,找到最新版本。
返回每组中最新版本的记录。
我尝试在 SQLAlchemy 中这样实现它:
subquery = session.query(
MyTable,
func.row_number().over(
partition_by=MyTable.portfolio_id,
order_by=MyTable.version.desc()).label("row_number")
).subquery()
LOG.info("subquery is ".format(subquery))
current_config = session.query(subquery).filter(subquery.c.row_number <= 1)
但是日志显示查询的是这个:
SELECT anon_1.id AS anon_1_id,
anon_1.portfolio_id AS anon_1_portfolio_id,
anon_1.portfolio_name AS anon_1_portfolio_name,
anon_1.version AS anon_1_version,
anon_1.created_at AS anon_1_created_at,
anon_1.last_updated_at AS anon_1_last_updated_at,
anon_1.last_updated_by AS anon_1_last_updated_by,
anon_1.config AS anon_1_config,
anon_1.row_number AS anon_1_row_number
FROM (
SELECT config_table_development.id AS id,
config_table_development.portfolio_id AS portfolio_id,
config_table_development.portfolio_name AS portfolio_name,
config_table_development.version AS version,
config_table_development.created_at AS created_at,
config_table_development.last_updated_at AS last_updated_at,
config_table_development.last_updated_by AS last_updated_by,
config_table_development.config AS config,
row_number() OVER (
PARTITION BY config_table_development.portfolio_id ORDER BY config_table_development.version DESC
) AS row_number
FROM config_table_development
) AS anon_1
WHERE anon_1.row_number <= ?
我们绝对不会期待WHERE anon_1.row_number <= ?
,我们应该期待WHERE anon_1.row_number <= 1
。我该如何解决?
【问题讨论】:
【参考方案1】:问题中的SQL语句是参数化版本的语句和
WHERE anon_1.row_number <= ?
显示 where 子句及其参数占位符。问题没有显示的是参数 value 将立即出现在日志中:
2022-03-14 18:15:26,664 INFO … SELECT anon_1.id AS anon_1_id, …
WHERE anon_1.row_number <= ?
2022-03-14 18:15:26,665 INFO … [generated in 0.00033s] (1,)
这就是1
的来源。
【讨论】:
以上是关于在 sqlalchemy 中实现窗口函数时需要帮助的主要内容,如果未能解决你的问题,请参考以下文章