CASE WHEN with ORM (SQLalchemy)

前端 未结 3 1919
孤独总比滥情好
孤独总比滥情好 2021-02-06 22:24

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 ?

3条回答
  •  臣服心动
    2021-02-06 22:54

    I got this to work with an aggregate function, in this case func.sum

    My Example Code

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

    My Use Case

    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

提交回复
热议问题