所以我有一个带有日期戳和两个字段的表,我想确保它们在上个月是唯一的。
table.id
table.datestamp
table.field1
table.field2
上个月应该没有相同的field1 + 2复合值的重复记录。
我脑子里的步骤是:
我已经走到了这一步,但我认为这不起作用:
result = session.query(table).group_by(\
table.field1,
table.field2,
func.month(table.timestamp))
但我不确定如何在sqlalchemy中这样做。有人可以告诉我吗?
非常感谢!
答案 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)
)