1. 程式人生 > >【Flask】Sqlalchemy group_by having

【Flask】Sqlalchemy group_by having

rst .com group_by mar pri ger flask () code

### 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

【Flask】Sqlalchemy group_by having