简体   繁体   English

如何合并 SQLAlchemy 中的两个计数查询?

[英]How to union two counts queries in SQLAlchemy?

I have two queries and the only difference between then is that one is counting the success status and the other failure status.我有两个查询,唯一的区别是一个是计算成功状态,另一个是失败状态。 Is there a way to get this result in just one query?有没有办法在一个查询中得到这个结果? I'm using SQLALchemy to do the queries.我正在使用 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)
)

You can use conditions on Count, your quer will look like您可以在 Count 上使用条件,您的查询看起来像

success_status_query = (
    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)

you can use the or_() operator like the sample bellow:您可以像下面的示例一样使用 or_() 运算符:

from sqlalchemy import or_

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

It won't be a straight swap, but you will be able to work it out.这不会是一个直接的交换,但你将能够解决它。

You can find more information in the SQLAlchemy documentation: https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.or _ You can find more information in the SQLAlchemy documentation: https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.or _

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM