代码之家  ›  专栏  ›  技术社区  ›  0atman

SQLAlchemy:如何按两个字段分组和按日期筛选

  •  7
  • 0atman  · 技术社区  · 14 年前

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

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

    上个月不应存在具有相同字段1+2复合值的重复记录。

    我脑子里的步骤是:

    1. 按两个字段分组
    2. 回顾上个月的数据,确保不会发生这种独特的分组。

    我已经走了这么远了,但我不认为这行得通:

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

    但我不确定如何在sqlacalchemy中做到这一点。有人能给我建议吗?

    非常感谢!

    1 回复  |  直到 14 年前
        1
  •  17
  •   van    14 年前

    以下内容应将您指向正确的方向,另请参见内联注释:

    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)
          )