在查询中使用“group_by”时,从每个组中选择一个元素

时间:2011-11-01 07:06:50

标签: python sql sqlalchemy

我想知道如何在使用“group by”查询时从类中提取任意元素。例如:

class Post(Base):
    id = Column(Integer, primary_key=True)
    created = Column(DateTime)
    comments = Column(Integer)
    creator = Column(Integer, ForeignKey('user.id'))
    anonymous = Column(Boolean)

class User(Base):
    id = Column(Integer, primary_key=True)

如何创建输出的查询:

creator | total number of comments made on the creator's post | the time of the creator's last post

creator | total number of comments made on the creator's post | if any of the posts are anonymous

基本查询将是:

session = DBSession()
commsum = session.query(Post.creator, func.sum(Post.comments).label('totalcomments')).\
    group_by(Post.creator).subquery()
return session.query(User, commsum.c.totalcomments).\
    join(commsum, commsum.c.creator == User.id).all()

如果我想返回1)每个group_by(Post.creator)或2中所有行的最新日期,如果任何行具有匿名== True,该怎么办?

1 个答案:

答案 0 :(得分:0)

在SQL中,您应该可以执行以下操作:

SELECT Post.creator, 
       sum(Post.comments) total_comments
       max(Post.Created) latest_post
       max(Post.anonymous) any_anonymous
FROM Post
GROUP BY Post.creator