【Flask】Sqlalchemy group_by having
### group_by:
根据某个字段进行分组。比如想要根据性别进行分组,来统计每个分组分别有多少人
### having:
having是对查找结果进一步过滤。比如只想要看未成年人的数量,那么可以首先对年龄进行分组统计人数,然后再对分组进行having过滤。示例代码如下:
1 # coding:utf-8 2 # Author: liangjun.chen 3 4 from datetime import datetime 5 from sqlalchemy import create_engine, Column, Integer, String, Enum, func 6 7 from sqlalchemy.ext.declarative import declarative_base 8 from sqlalchemy.orm import sessionmaker, relationship, backref 9 10 HOSTNAME = '127.0.0.1' 11 PORT = 3306 12 DATABASE = 'sqlalchemy_first' 13 USERNAME = 'root' 14 PASSWORD = '123456' 15 16 DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'.format( 17 username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, dbname=DATABASE 18 ) 19 engine = create_engine(DB_URI) 20 Base = declarative_base(engine) 21 Session = sessionmaker(engine) 22 session = Session() 23 24 25 26 class User(Base): 27 __tablename__ = 'user' 28 id = Column(Integer, primary_key=True, autoincrement=True) 29 username = Column(String(50), nullable=False) 30 age = Column(Integer, default=0) 31 gender = Column(Enum('male', 'female', "secret"), default='male') 32 33 def __repr__(self): 34 return "User<{}>".format(self.username) 35 # Base.metadata.drop_all() 36 # Base.metadata.create_all() 37 # 38 # user = User(username='saber', age=17, gender='male') 39 # user2 = User(username='saber2', age=18, gender='male') 40 # user3 = User(username='saber3', age=18, gender='female') 41 # user4 = User(username='saber4', age=19, gender='female') 42 # user5 = User(username='saber5', age=19, gender='female') 43 # 44 # session.add_all([user, user2, user3, user4, user5]) 45 # session.commit() 46 47 # group_by 48 49 users = session.query(User.age, func.count(User.id)).group_by(User.age) 50 print users.all() 51 52 # having 53 users = session.query(User.age, func.count(User.id)).group_by(User.age).having(User.age>18).all() 54 print users