Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: How to group by two fields and filter by date

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:

  1. Group by the two fields
  2. Look back over the last month's data to make sure this unique grouping doesn't occur.

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!

like image 779
0atman Avatar asked Jun 15 '10 10:06

0atman


1 Answers

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

like image 97
van Avatar answered Oct 18 '22 07:10

van