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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.