SQLAlchemy MySQL IF 문
-
23-12-2019 - |
문제
나는 오래된 레거시 PHP 시스템을 플라스크 + SQLAlchemy로 변환하고 내가 어떻게 다음을 구성하는지 궁금해하고있었습니다.
모델이 있습니다.
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
.
이 쿼리를 구성하는 SQLAlchementish 방법이 있습니까?- SqlAlchemy를 사용하는 경우 MySQL을 위해 Googling을 시도했지만 공백을 그렸습니다.
많은 감사합니다!
해결책
func
(설명서) 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
. 제휴하지 않습니다 StackOverflow