SQLAlchemy:如何按两个字段分组并按日期过滤

时间:2010-06-15 10:52:54

标签: python sql mysql sqlalchemy group-by

所以我有一个带有日期戳和两个字段的表,我想确保它们在上个月是唯一的。

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

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

我脑子里的步骤是:

  1. 按两个字段分组
  2. 回顾过去一个月的数据,以确保不会发生这种独特的分组。
  3. 我已经走到了这一步,但我认为这不起作用:

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

    但我不确定如何在sqlalchemy中这样做。有人可以告诉我吗?

    非常感谢!

1 个答案:

答案 0 :(得分:18)

以下内容应指向正确的方向,也请参阅内联评论:

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)
      )
相关问题