How to solve error “Operator 'getitem' is not supported on this expression” when using case()

一笑奈何 提交于 2020-12-21 03:52:37

问题


I'm trying to convert the following SQL into 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

I've got as far as:

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)

But I'm getting the following error:

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

On the line:

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

SO won't let me post the whole traceback as it says there is too much code!

Where am I going wrong?


回答1:


case takes a list of when criteria as its first argument, so you need to bracket accordingly:

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

So your code should look like this:

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)




回答2:


This doesn't directly answer your question, but I have had much more luck in the past using pyodbc and pandas for SQL querying, and then you wouldn't need to translate your query either

import pandas as pd
import pyodbc

conn = pyodbc.connect("<Insert connection string here>")
sql = """
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
"""
df = pd.read_sql(sql, conn)


来源:https://stackoverflow.com/questions/64857004/how-to-solve-error-operator-getitem-is-not-supported-on-this-expression-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!