sqlalchemy COUNT和IF

时间:2010-10-19 20:29:49

标签: count sqlalchemy

任何人都知道如果在SQL炼金术中如何计算

COUN(IF(table_row = 1 AND table_row2 =2),1,0)

我做了这样的事,

func.COUNT(func.IF((TransactionMessage.tm_read==0 and TransactionMessage.tm_type==1),1,0)).label('t_message_count'),

但是如果使用TransactionMesssage.tm_read,sqlalchemy会分开2个, 和TransactinMessage.tm_type

可以帮助我解决问题吗?

1 个答案:

答案 0 :(得分:9)

我没有要测试的环境,但很可能你需要使用sqlalchemy.sql.expression.and_表达式:

from sqlalchemy.sql.expression import and_
...
func.COUNT(func.IF(and_(TransactionMessage.tm_read == 0, 
                        TransactionMessage.tm_type == 1), 1, 0)
           ).label('t_message_count'),