2011-11-01 20 views
0

我想知道如何在查詢「group by」時從類中提取任意元素。例如:當在查詢中使用「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。

+0

你在此刻得到了什麼?你有什麼嘗試? (請用這個信息更新你的問題。) –

+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 
相關問題