【问题标题】:group by and count in sqlalchemy在 sqlalchemy 中分组和计数
【发布时间】:2021-08-31 14:52:41
【问题描述】:

我有一个下表:

conn.execute(hotel.insert(), [
   {'country':'India', 'city' : 'Pune', 'name': 'name1'},
   {'country':'India', 'city' : 'Mumbai', 'name': 'name2'},
   {'country':'India', 'city' : 'Nagpur', 'name': 'name3'},
   {'country':'US', 'city' : 'San Jose', 'name': 'name4'},
   {'country':'US', 'city' : 'San Francisco', 'name': 'name5'},
   {'country':'US', 'city' : 'San Mateo', 'name': 'name6'},
   {'country':'Brazil', 'city' : 'abc', 'name': 'name7'},
   {'country':'Brazil', 'city' : 'pqr', 'name': 'name8'},
   {'country':'Brazil', 'city' : 'xyz', 'name': 'name9'},
   {'country':'India', 'city' : 'Pune', 'name': 'name10'},
   {'country':'India', 'city' : 'Pune', 'name': 'name11'},
   {'country':'US', 'city' : 'San Jose', 'name': 'name12'},
   {'country':'Brazil', 'city' : 'abc', 'name': 'name13'},
])

我想为每个国家/地区找出一个拥有最多条目数的城市。

我遵循this 示例并通过以下查询获得此输出: 查询:

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
from sqlalchemy import func
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///hotel.db', echo = True)
meta = MetaData()

hotel = Table(
   'hotel', meta,
   Column('country', String),
   Column('city', String),
   Column('name', String),
)

Session = sessionmaker(bind = engine)
session = Session()
print(session.query(hotel.columns.city, func.count(hotel.columns.city)).group_by(hotel.columns.country).all())

输出:

[('abc', 4), ('Pune', 5), ('San Jose', 4)]

它给出了所有城市的最大条目,但显示的计数是一个国家的条目数?不知道 sqlalchemy 是如何工作的,如果它幼稚的话,抱歉。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    您需要使用子查询来计算每个国家/地区的城市,然后从子查询的计数中选择最大值:

    subq = select(hotel.c.country,
                  hotel.c.city,
                  func.count(hotel.c.city)
                  .label('count'))\
                  .group_by(hotel.c.country,
                            hotel.c.city)\
                  .subquery()
    stmt = select(subq.c.city,
                  subq.c.count)\
                  .having(func.max(subq.c.count))\
                  .group_by(subq.c.country)
    print(session.execute(stmt).all())
    

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多