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.
JavaScript
x
7
1
success_status_query = (
2
db_session.query(Playbook.operator, func.count(Playbook.operator).label("success"))
3
.filter(Playbook.opname != "failed")
4
.join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
5
.group_by(Playbook.operator)
6
)
7
JavaScript
1
7
1
failure_status_query = (
2
db_session.query(Playbook.operator, func.count(Playbook.operator).label("failure"))
3
.filter(Playbook.opname == "failed")
4
.join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
5
.group_by(Playbook.operator)
6
)
7
Advertisement
Answer
You can use conditions on Count, your query will look like:
JavaScript
1
20
20
1
query = (
2
db_session.query(
3
Playbook.operator,
4
func.count(
5
case(
6
[((Playbook.opname != "failed"), Playbook.operator)],
7
else_=literal_column("NULL"),
8
)
9
).label("success"),
10
func.count(
11
case(
12
[((Playbook.opname == "failed"), Playbook.operator)],
13
else_=literal_column("NULL"),
14
)
15
).label("failure"),
16
)
17
.join(AccountInfo, AccountInfo.hardware_id == Playbook.hardware_id)
18
.group_by(Playbook.operator)
19
)
20