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

0at*_*man 8 python mysql sql group-by sqlalchemy

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

table.id
table.datestamp
table.field1
table.field2
Run Code Online (Sandbox Code Playgroud)

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

我脑子里的步骤是:

  1. 由两个领域组成
  2. 回顾上个月的数据,以确保不会发生这种独特的分组.

我已经走到了这一步,但我认为这不起作用:

result = session.query(table).group_by(\
    table.field1,
    table.field2,
    func.month(table.timestamp))
Run Code Online (Sandbox Code Playgroud)

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

非常感谢!

van*_*van 19

下面应该指出你正确的方向,也看到内联评论:

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)
      )
Run Code Online (Sandbox Code Playgroud)

  • @van:我爱你.它是如此简单和干净我甚至没想到...... (2认同)