2010-06-15 151 views
6

因此,我有一张带有日期戳记和两个字段的表格,我想确保它们在上个月是唯一的。SQLAlchemy:如何按两个字段进行分组并按日期过滤

table.id 
table.datestamp 
table.field1 
table.field2 

上个月应该没有重复的记录与相同的field1 + 2复合值。

在我脑海中的步骤是:

  1. 集团由两个字段
  2. 回首过去一个月的数据,以确保这种独特的分组不会发生。

我远了,但我不认为这个工程:

result = session.query(table).group_by(\ 
    table.field1, 
    table.field2, 
    func.month(table.timestamp)) 

但我不确定如何在SQLAlchemy中做到这一点。有人能劝我吗?

非常感谢!

+0

谢谢,伙计们 – 0atman 2010-06-15 10:54:18

回答

15

下面应该指向你在正确的方向,也看在线评论:提前

qry = (session.query(
       table.c.field1, 
       table.c.field2, 
       # #strftime* for year-month works on sqlite; 
       # @todo: find proper function for mysql (as in the question) 
       # Also it is not clear if only MONTH part is enough, so that 
       # May-2001 and May-2009 can be joined, or YEAR-MONTH must be used 
       func.strftime('%Y-%m', table.c.datestamp), 
       func.count(), 
       ) 
     # optionally check only last 2 month data (could have partial months) 
     .filter(table.c.datestamp < datetime.date.today() - datetime.timedelta(60)) 
     .group_by(
       table.c.field1, 
       table.c.field2, 
       func.strftime('%Y-%m', table.c.datestamp), 
       ) 
     # comment this line out to see all the groups 
     .having(func.count()>1) 
    ) 
+0

非常感谢面包车,但您的解决方案戳孔在我的SQLAlchemy知识,什么是意义表对象的'c'属性? – 0atman 2010-06-16 09:53:50

+0

如果你有一个'table'对象,那么'c'是'columns'的快捷方式。请参阅SQL表达式语言教程:http://www.sqlalchemy.org/docs/sqlexpression.html?highlight=group_by#ordering-grouping-limiting-offset-ing – van 2010-06-16 10:21:30

+0

不要担心,我应该只是在Google上搜索我的问题,因为情况经常是这样! – 0atman 2010-06-16 10:29:17