1

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.

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)
)
0

2 Answers 2

2

You can use conditions on Count, your query will look like:

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)
)
Sign up to request clarification or add additional context in comments.

Comments

0

you can use the or_() operator like the sample bellow:

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_

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.