SQLAlchemy func.count on boolean column

前端 未结 3 933
南方客
南方客 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:30

    You can use this query:

    Session.query(func.sum(case([(Question.accepted == True, 1)], else_=0).label('accepted_number'))
    

    And the same column will be for False value, but with False in condition

    Or, you can use window function:

    Session.query(func.count(Question.id).over(partition_by=Question.accepted), Question.accepted).all()
    

    The result will contain two rows (if there are only two possible values in Question.accepted), where the first column is the number of values, and the second is the values of 'accepted' column.

提交回复
热议问题