2014-02-27 90 views
3

我在轉換的舊的遺留PHP系統瓶+ SQLAlchemy的中間,不知道我怎麼會構造如下:SQLAlchemy的MySQL的IF語句

我有一個模型:

class Invoice(db.Model): 
    paidtodate = db.Column(DECIMAL(10,2)) 
    fullinvoiceamount = db.Column(DECIMAL(10,2)) 
    invoiceamount = db.Column(DECIMAL(10,2)) 
    invoicetype = db.Column(db.String(10)) 
    acis_cost = db.Column(DECIMAL(10,2)) 

我需要運行的查詢是:

SELECT COUNT(*) AS the_count, sum(if(paidtodate>0,paidtodate,if(invoicetype='CPCN' or invoicetype='CPON' or invoicetype='CBCN' or invoicetype='CBON' or invoicetype='CPUB' or invoicetype='CPGU' or invoicetype='CPSO',invoiceamount, 
fullinvoiceamount))) AS amount, 
SUM(acis_cost) AS cost, (SUM(if(paidtodate>0,paidtodate,invoiceamount))-SUM(acis_cost)) AS profit FROM tblclientinvoices 

是否有SQLAlchemyish方法來構造此查詢? - 我試過用SQlAlchemy搜索Mysql IF語句,但畫空白。

非常感謝!

+1

在使用'case'表達式([文檔]看看(http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement .html#sqlalchemy.sql.expression.case)) – alecxe

回答

6

使用func(documentation)生成SQL函數表達式:

qry = select([ 
     func.count().label("the_count"), 

     func.sum(func.IF(
      Invoice.paidtodate>0, 
      Invoice.paidtodate, 
      # @note: I prefer using IN instead of multiple OR statements 
      func.IF(Invoice.invoicetype.in_(
        ("CPCN", "CPON", "CBCN", "CBON", "CPUB", "CPGU", "CPSO",) 
       ), 
       Invoice.invoiceamount, 
       Invoice.fullinvoiceamount) 
      ) 
     ).label("amount"), 

     func.sum(Invoice.acis_cost).label("Cost"), 

     (func.sum(func.IF(
      Invoice.paidtodate>0, 
      Invoice.paidtodate, 
      Invoice.invoiceamount 
      )) 
      - func.sum(Invoice.acis_cost) 
     ).label("Profit"), 
    ], 
) 

rows = session.query(qry).all() 
for row in rows: 
    print row 
+0

非常感謝您的幫助。 –