How to use sum and order by in SQLAlchemy query

Viewed 5308

I'm trying to return a sum row from my table and order with the sum result.

My sql like this:

self.db_user_online.query(
    MeleeGameData,
    func.sum(MeleeGameData.core_data).label("ct")
).\
    group_by(MeleeGameData.ccid).\
    filter_by(mid=self.cycle_id).\
    order_by("ct desc").\
    all()

Debug echo sql:

SELECT fiels..., sum(t_act_melee_game_data.core_data) AS ct
FROM t_act_melee_game_data
WHERE t_act_melee_game_data.mid = %s
GROUP BY t_act_melee_game_data.ccid
ORDER BY ct DESC

But it's can't work..

2 Answers

you could try

self.db_user_online.query(
    MeleeGameData,
    func.sum(MeleeGameData.core_data).label("ct")
) \
    .group_by(MeleeGameData.ccid) \
    .filter_by(mid=self.cycle_id) \
    .order_by(desc("ct")) \
    .all()
Related