【问题标题】:How to union two counts queries in SQLAlchemy?如何在 SQLAlchemy 中合并两个计数查询?
【发布时间】:2022-08-14 07:35:39
【问题描述】:

我有两个查询,唯一的区别是一个是计算成功状态,另一个是失败状态。有没有办法在一个查询中得到这个结果?我正在使用 SQLALchemy 进行查询。

success_status_query = (
    db_session.query(Playbook.operator, func.count(Playbook.operator).label(\"success\"))
    .filter(Playbook.opname != \"failed\")
    .join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
    .group_by(Playbook.operator)
)
failure_status_query = (
    db_session.query(Playbook.operator, func.count(Playbook.operator).label(\"failure\"))
    .filter(Playbook.opname == \"failed\")
    .join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
    .group_by(Playbook.operator)
)
  • 你可以和q1.union(q2)做一个简单的联合,但是可能很难区分成功和失败的结果。

标签: python sql sqlalchemy fastapi


【解决方案1】:

您可以在 Count 上使用条件,您的查询看起来像

stmt = (
    db_session.query(
        Playbook.operator,
        func.count(
            case(
                [((Playbook.opname != "failed"), Playbook.operator)],
                else_=literal_column("NULL"),
            )
        ).label("success"),
        func.count(
            case(
                [((Playbook.opname == "failed"), Playbook.operator)],
                else_=literal_column("NULL"),
            )
        ).label("failure"),
    )
    .join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
    .group_by(Playbook.operator)
)

【讨论】:

    【解决方案2】:

    您可以使用 or() 运算符,如下例所示:

    from sqlalchemy import or_
    
    stmt = select(users_table).where(
                    or_(
                        users_table.c.name == 'wendy',
                        users_table.c.name == 'jack'
                    )
                )
    

    这不会是一个直接的交换,但你将能够解决它。

    您可以在 SQLAlchemy 文档中找到更多信息: https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.or_

    【讨论】:

      猜你喜欢
      • 2022-08-04
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多