zoukankan      html  css  js  c++  java
  • group_by和having的用法

    #encoding: utf-8
    
    from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Enum
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    from random import randint
    
    HOSTNAME = '127.0.0.1'
    
    PORT = 3306
    
    DATABASE = 'first_sqlalchemy'
    
    USERNAME = 'root'
    
    PASSWORD = '123456'
    
    #dialect+driver://username:password@host:port/database
    DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" 
             "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)
    
    engine = create_engine(DB_URI)
    
    Base = declarative_base(engine)
    
    # Session = sessionmaker(engine)
    # session = Session()
    
    session = sessionmaker(engine)() #Session(**local_kw)
    
    
    class User(Base):
        __tablename__ = 'user'
        id = Column(Integer,primary_key=True,autoincrement=True)
        username = Column(String(50),unique=True,nullable=False)
        age = Column(Integer,default=0)
        gender = Column(Enum('male','female','secret'),default='male')
    
    
    # Base.metadata.drop_all()
    #
    # Base.metadata.create_all()
    #
    # user1 = User(username='小一',age=17,gender='male')
    # user2 = User(username='小二',age=18,gender='male')
    # user3 = User(username='小三',age=19,gender='male')
    # user4 = User(username='小四',age=20,gender='female')
    # user5 = User(username='小五',age=21,gender='female')
    # user6 = User(username='小六',age=22,gender='male')
    #
    # session.add_all([user1,user2,user3,user4,user5,user6])
    # session.commit()
    
    #用group_by根据年龄来分组
    result = session.query(User.gender,func.count(User.id)).group_by(User.gender)
    print(result)
    '''
    SELECT user.gender AS user_gender, count(user.id) AS count_1 
    FROM user GROUP BY user.gender
    
    '''
    
    #用group_by和having一起用
    
    ret = session.query(User.gender,func.count(User.id)).group_by(User.gender).having(User.age>20)
    print(ret)
    
    '''
    SELECT user.gender AS user_gender, count(user.id) AS count_1, user.age AS user_age 
    FROM user GROUP BY user.gender 
    HAVING user.age > %(age_1)s
    '''

  • 相关阅读:
    The Tower of Hanoi
    POJ 3259:Wormholes
    第二数学归纳法
    Josephus Problem
    想成为Java高手的25个学习目标
    How to find a cycle of length 4?
    Fabonacci Numbers
    通过参数离线安装SharePoint 2010[转]
    Sharepoint2010文档库权限问题
    BizTalk 2010 学习笔记——第一章 BizTalk 2010 概述
  • 原文地址:https://www.cnblogs.com/wuheng-123/p/9718439.html
Copyright © 2011-2022 走看看