2010-06-15 46 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

相關問題