SQLAlchemy func.count on boolean column

前端 未结 3 934
南方客
南方客 2020-12-07 04:15

How can I count easily the number of rows where a particular column is true and the number where it is false ?

I can\'t (or can I ?) run t

3条回答
  •  一个人的身影
    2020-12-07 04:28

    Most flavors of SQL store booleans as 1-bit integers, and calling SUM on them properly gives you the number of positive booleans/True rows. In your case, you can simply do:

    func.sum(Question.accepted)
    

    If your SQL engine returns a SUM of booleans as a boolean (not sure there is any), you can use expression function cast() to force it into an integer instead of using func.count(case([(Question.accepted, 1)])):

    func.sum(sqlalchemy.cast(Question.accepted, sqlalchemy.Integer))
    

    Finally, if you want the sum as an integer on the Python side the expression function type_coerce() does the trick:

    sqlalchemy.type_coerce(func.sum(Question.accepted), sqlalchemy.Integer)
    

提交回复
热议问题