### group_by:
根据某个字段进行分组。比如想要根据性别进行分组,来统计每个分组分别有多少人

### having:

having是对查找结果进一步过滤。比如只想要看未成年人的数量,那么可以首先对年龄进行分组统计人数,然后再对分组进行having过滤。示例代码如下:

 # coding:utf-8
# Author: liangjun.chen from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, Enum, func from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref HOSTNAME = '127.0.0.1'
PORT = 3306
DATABASE = 'sqlalchemy_first'
USERNAME = 'root'
PASSWORD = '' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'.format(
username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, dbname=DATABASE
)
engine = create_engine(DB_URI)
Base = declarative_base(engine)
Session = sessionmaker(engine)
session = Session() class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
age = Column(Integer, default=0)
gender = Column(Enum('male', 'female', "secret"), default='male') def __repr__(self):
return "User<{}>".format(self.username)
# Base.metadata.drop_all()
# Base.metadata.create_all()
#
# user = User(username='saber', age=17, gender='male')
# user2 = User(username='saber2', age=18, gender='male')
# user3 = User(username='saber3', age=18, gender='female')
# user4 = User(username='saber4', age=19, gender='female')
# user5 = User(username='saber5', age=19, gender='female')
#
# session.add_all([user, user2, user3, user4, user5])
# session.commit() # group_by users = session.query(User.age, func.count(User.id)).group_by(User.age)
print users.all() # having
users = session.query(User.age, func.count(User.id)).group_by(User.age).having(User.age>18).all()
print users
05-11 18:07