以下SQLAlchemy查询编译为非法MSSQL。看起来生成的MSSQL正在尝试按原始的非聚合列而不是SQLAlchemy查询中指定的聚合列进行排序。如果我更改聚合列的标签,这个问题就会消失;但是,对于我们的应用程序而言,此列与其聚合的列具有相同的名称非常重要。过去几天我一直在搜索谷歌,但我没有找到任何有用的建议;有人可以帮助我理解我做错了什么或如何解决这个问题?
price_sum = sqlalchemy.func.sum(
table.c['Opportunity Max Amount']
).label('Opportunity Max Amount')
query = sqlalchemy.select(
columns=[price_sum],
order_by=sqlalchemy.desc(price_sum),
offset=1,
).alias("FOO")
rows = conn.execute(query).fetchall()
生成的MSSQL:
SELECT anon_1.[Opportunity Max Amount]
FROM (
SELECT
sum([table_name].[Opportunity Max Amount]) AS [Opportunity Max Amount],
ROW_NUMBER() OVER (ORDER BY [Opportunity Max Amount] DESC) AS mssql_rn
FROM [table_name]
) AS anon_1
WHERE mssql_rn > 1
生成的Postgres查询(此查询按预期工作,此处提供作为我正在尝试完成的内容的参考):
SELECT
sum(performance_data."Opportunity Max Amount") AS "Opportunity Max Amount"
FROM performance_data
ORDER BY "Opportunity Max Amount" DESC
LIMIT ALL
OFFSET 1
错误消息:
sqlalchemy.exc.OperationalError: (pymssql.OperationalError) (8120, b"Column
'table_name.Opportunity Max Amount' is invalid in the
select list because it is not contained in either an aggregate function or the
GROUP BY clause.DB-Lib error message 20018, severity 16:\nGeneral SQL Server
error: Check messages from the SQL Server\n") [SQL: 'SELECT anon_1.[Opportunity
Max Amount] \nFROM (SELECT sum([table_name].[Opportunity
Max Amount]) AS [Opportunity Max Amount], ROW_NUMBER() OVER (ORDER BY
[Opportunity Max Amount] DESC) AS mssql_rn \nFROM
[table_name]) AS anon_1 \nWHERE mssql_rn > %(param_1)s']
[parameters: {'param_1': 1}]
答案 0 :(得分:0)
看起来这是SQLAlchemy的一个错误,修复工作正在进行中:
https://groups.google.com/forum/#!topic/sqlalchemy/1FKTBa9BMIE