在选择查询中使用“case”sqlalchemy抛出异常

时间:2016-12-08 23:29:57

标签: python postgresql sqlalchemy

我正在尝试将此sql查询构建到sqlalchemy:

select distinct
    processed_by_user_uuid,
    sum(case when audited_result_uuid = PASSED_RESULT_UUID then 1 else 0 end) as "passed",
    sum(case when audited_result_uuid <> PASSED_RESULT_UUID then 1 else 0 end) as "failed",
    count(distinct processed_using) as "total audits"
from audit
where
    audited_at is not null
    and processed_at > [start_time]
    and processed_at < [end_time]
group by 1

我的尝试:

query = Session.query(audit_table).with_entities(
    audit_table.c.processed_by_user_uuid,
    func.sum(
        case([audit_table.c.audited_result_uuid == PASSED_RESULT_UUID, 1], else_=0)
    ).label('passed'),
    func.sum(
        case([audit_table.c.audited_result_uuid != PASSED_RESULT_UUID, 1], else_=0)
    ).label('failed'),
    func.count(distinct(audit_table.c.processed_using)).label('total audits')
).filter(
    audit_table.c.audited_at is not None,
    audit_table.c.processed_at > start_time,
    audit_table.c.processed_at < end_time
).group_by(
    1
)

当我尝试这个时,我得到了例外:

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

从一些挖掘中,对这一行感到不满:

func.sum(
    case([audit_table.c.audited_result_uuid == PASSED_RESULT_UUID, 1], else_=0)
).label('passed')

1 个答案:

答案 0 :(得分:4)

您没有正确使用case(...) - 您需要将您的条件设置为(condition, value)的元组,以便:

case([audit_table.c.audited_result_uuid == PASSED_RESULT_UUID, 1], else_=0)

变为:

case([(audit_table.c.audited_result_uuid == PASSED_RESULT_UUID, 1)], else_=0)

同样适用于其他case声明。

此外,您的过滤条件audit_table.c.audited_at is not None不会导致您尝试构建的查询。此表达式将评估为boolean的{​​{1}}值,因此会生成 truthy True子句,例如WHERE(或根本没有)。
相反,您应该使用WHERE 1=1。 PEP-8检查会抱怨,但这应该与sqlalchemy一起使用。