I am using SQLAlchemy with the ORM paragdim. I don\'t manage to find a way to do a CASE WHEN instruction. I don\'t find info about this on the web.
Is it possible ?
I got this to work with an aggregate function, in this case func.sum
from sqlalchemy import func, case
my_case_stmt = case(
[
(MyTable.hit_type.in_(['easy', 'medium']), 1),
(MyTable.hit_type == 'hard', 3)
]
)
score = db.session.query(
func.sum(my_case_stmt)
).filter(
MyTable.success == 1
)
return score.scalar()
MyTable looks like this:
| hit_type | success |
-----------------------------
| easy | 1 |
| medium | 1 |
| easy | 0 |
| hard | 1 |
| easy | 0 |
| easy | 1 |
| medium | 1 |
| hard | 1 |
score
is computed as such:
score = num_easy_hits + num_medium_hits + (3 * num_hard_hits)
4 successful easy/medium hits and 2 successful hard hits gives you (4 + (2*3)) = 10