I have a table of tennis matches and I would like to create a query field that counts the number of previous matches within a date range of the date of the focal match. For example:
+----------+------------+---------------------------+
| match_id | date | num_matches within 3 days |
+----------+------------+---------------------------+
| 1 | 01/01/2020 | 0 |
| 2 | 02/01/2020 | 1 |
| 3 | 03/01/2020 | 2 |
| 4 | 05/01/2020 | 2 |
| 5 | 05/01/2020 | 3 |
| 6 | 10/01/2020 | 0 |
+----------+------------+---------------------------+
I've tried using a correlated sub-query as set out here but I can't figure out how to create the conditions:
@hybrid_method
def match_count(self, timespan_days):
cut_off = self.date_time_inferred - timedelta(days=timespan_days)
return sum(x >= cut_off and <some_cond_for_less_than_current_match_date> for x in self.date_time_inferred)
@match_count.expression
def match_count(cls, timespan_days):
cut_off = cls.date_time_inferred - timedelta(days=timespan_days)
return (
select(func.count(cls.date_time_inferred)).
where(
and_(
cls.date_time_inferred.__ge__(cut_off),
cls.date_time_inferred.__lt__(<not_sure_what_goes_here>),
)
).label('match_count')
)
In trialling simpler forms of the above I also kept getting the following error:
sqlalchemy.exc.ArgumentError: columns argument to select() must be a Python list or other iterable
On the code:
select(func.count(cls.date))
So I'm clearly doing a whole heap of stuff wrong.
Hopefully someone can help me understand how to fix this? Also very open to different ways to accomplish the same thing. I would like to stick with a hybrid attribute though...
from How to build a hybrid_method that counts the number of records from the last X days?
No comments:
Post a Comment