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..
We first extract the average value of the percentage column using SQLalchemy's `func. avg()` function. Then we use the `func. sum()` function to get the sum of the values in the percentage column.
Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.
method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.
The Sequence object represents the name and configurational parameters of a database sequence. It also represents a construct that can be “executed” by a SQLAlchemy Engine or Connection , rendering the appropriate “next value” function for the target database and returning a result.
Starting with your SQL code; I suppose you want to group by every ccid
and then sum the corresponding data (I took out the filter for simplicity):
SELECT t_act_melee_game_data.ccid,
sum(t_act_melee_game_data.core_data) AS ct
FROM t_act_melee_game_data
GROUP BY t_act_melee_game_data.ccid
ORDER BY sum(t_act_melee_game_data.core_data) DESC
Construct in SQLAlchemy;
self.db_user_online.query(
MeleeGameData.ccid,
func.sum(MeleeGameData.core_data).label("ct")
).\
group_by(MeleeGameData.ccid).\
order_by(func.sum(MeleeGameData.core_data).desc()).\
all()
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()
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