So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month.
table.id
table.datestamp
table.field1
table.field2
There should be no duplicate record with the same field1 + 2 compound value in the last month.
The steps in my head are:
I've got this far, but I don't think this works:
result = session.query(table).group_by(\
table.field1,
table.field2,
func.month(table.timestamp))
But I'm unsure how to do this in sqlalchemy. Could someone advise me?
Thanks very much!
Following should point you in the right direction, also see inline comments:
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With