I have a request in sqlachemy with SQLite which return an object of the group by and a value (avg) :
result = session.query(
obj, func.avg(obj.value).label("value_avg")
).group_by(
func.strftime('%s', obj.date)
).all()
But now i need to use postgresql which is more restrictive (strict SQL) and i need to do the same thing but it need to replace query(obj) by something in the group by like func.avg() or something else. So i would like to know if exist any func which can be able to return the first obj of each group. If not possible maybe i can implement comparator for my obj and for instance call func.min(obj) like this :
result = session.query(
func.min(obj), func.avg(obj.value).label("value_avg")
).group_by(
func.date_part('second', obj.date)
).all()
And maybe implement cmp and eq in my obj model ? (What is the best practice)
EDIT :
I got a workaround but i'm not sure it's a good practice. First group by and next join :
sq = session.query(
func.min(obj.date).label("date"), func.avg(obj.value).label("value_avg")
).group_by(
func.cast(func.extract('second', obj.date) / 600, Integer)
).order_by(obj.date).subquery()
result = session.query(obj, sq.c.value_avg).join(sq,sq.c.date == obj.date).all()
What i want is the first obj of each group and value_avg of the group
min()is unique (which I guess it is, becauseidsound like a primary key; but if it's only a foreign key, that might not be the case). -- This is a specialized case of greatest-n-per-group (where N=1). There are a plenty of SQL solutions already here on SO, but I don't know which is the most suitable for SQLAlchemy.SELECT min(date) ... GROUP BY dateandSELECT date ... GROUP BY dateis the same (there is only onedatein thedategroup anyway). -- Also, a single index doesn't guarantee its uniqueness.query(obj, func.avg(obj.value).label("value_avg"))which give me access to obj attributs