這里我們要用到的query
對象的方法:
.filter_by(..)
.group_by(..)
.having(..)
我們需要額外導(dǎo)入的方法:
from sqlalchemy import func
func
方法主要用來做統(tǒng)計(jì)拍霜,映射到sql語句中具體的統(tǒng)計(jì)方法贩疙,如:
func.count(..)
func.sum(..)
func方法的格式為:func('字段名').label('顯示名')
SQL語句的用法如下:
SELECT school, COUNT(*) AS c FROM persons WHERE gender="male" GROUP BY age
SQLAlchemy中如下:
from sqlalchemy import func
results = sessin.query( Person.school, func.count('*').label('c') ).filter(
Person.gender=='male'
).group_by( Person.age )
篩選
SQL中針對Group By還可以再進(jìn)一步篩選爽丹,但是要用另一個(gè)關(guān)鍵詞Having
。
SQL語句的用法如下:
SELECT school, COUNT(*) AS c FROM persons WHERE gender="male" GROUP BY age HAVING c >1
SQLAlchemy中如下:
nums = func.count('*').label('c')
results = sessin.query( Person.school, nums ).filter(
Person.gender=='male'
).group_by(
Person.age
).having(
nums > 10
)