gpt4 book ai didi

python - 如何解决错误 "Operator ' getitem' is not supported on this expression"when using case()

转载 作者:行者123 更新时间:2023-12-05 02:03:50 25 4
gpt4 key购买 nike

我正在尝试将以下 SQL 转换为 SQLAlchemy:

select t1.id, t1.field_A,
max(case when t2.field_B = 1 then t2.field_C end) test_2_field_b_1,
max(case when t2.field_B = 2 then t2.field_C end) test_2_field_b_2
from test_1 t1
inner join test_2 t2 on t2.field_A = t1.field_A
group by t1.id, t1.field_A

我已经做到了:

qry = session.query(
Test1.id_,
Test2.field_A,
func.max(case((Test2.field_B.__eq__(1), "Test2.field_C"))).label("test_2_field_b_1"),
func.max(case((Test2.field_B.__eq__(2), "Test2.field_C"))).label("test_2_field_b_2"),
)
qry = qry.select_from(Test1)
qry = qry.join(Test2, Test2.field_A.__eq__(Test1.field_A))
qry = qry.group_by(Test1.id_, Test2.field_A)

但我收到以下错误:

NotImplementedError: Operator 'getitem' is not supported on this expression

线上:

func.max(case((Test2.field_B.__eq__(1), "Test2.field_C"))).label("test_2_field_b_1"),

所以不允许我发布整个回溯,因为它说代码太多了!

我哪里错了?

最佳答案

casewhen 条件的 list 作为其第一个参数,因此您需要相应地括起来:

sa.case([(Model.column == value, then_output)])

所以你的代码应该是这样的:

qry = session.query(
Test1.id_,
Test2.field_A,
sa.func.max(sa.case([(Test2.field_B == 1, "Test2.field_C")])).label("test_2_field_b_1"),
sa.func.max(sa.case([(Test2.field_B == 2, "Test2.field_C")])).label("test_2_field_b_2"),
)
qry = qry.select_from(Test1)
qry = qry.join(Test2, Test2.field_A == Test1.field_A)

关于python - 如何解决错误 "Operator ' getitem' is not supported on this expression"when using case(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64857004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com