【问题标题】:SQLAlchemy: How to group by two fields and filter by dateSQLAlchemy:如何按两个字段分组并按日期过滤
【发布时间】:2010-06-15 10:52:54
【问题描述】:

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

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 中执行此操作。有人可以给我建议吗?

非常感谢!

【问题讨论】:

    标签: python sql mysql sqlalchemy group-by


    【解决方案1】:

    以下应该为您指明正确的方向,另请参阅内联 cmets:

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

    【讨论】:

    • 非常感谢van,但是您的解决方案在我的sqlalchemy知识中戳了个洞,表对象的'c'属性有什么意义?
    • 如果你有一个table 对象,那么ccolumns 的快捷方式。请参阅 SQL 表达式语言教程:sqlalchemy.org/docs/…
    • 别担心,我应该用谷歌搜索我的问题,这种情况经常发生!
    • 然而,我意识到我们并没有使用原生 mysql 时间戳,实际上,我们使用 int(time.time()) 来存储时间,以与其他系统兼容。我将修改我的问题以包含此内容,也许我可以在最后 2,592,000 秒内仅添加时间戳检查? (30 天)
    • @van:我爱你。它是如此简单和干净,我什至不会想到...
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2022-06-11
    • 1970-01-01
    • 2020-08-25
    • 2017-08-04
    相关资源
    最近更新 更多