Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sum and order by in SQLAlchemy query

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

like image 726
steve Avatar asked Mar 17 '16 02:03

steve


People also ask

How do you sum in SQLAlchemy?

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.

How does the querying work with SQLAlchemy?

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.

What is all () in SQLAlchemy?

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.

What is sequence in SQLAlchemy?

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.


2 Answers

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()
like image 136
Joost Döbken Avatar answered Nov 26 '22 08:11

Joost Döbken


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()
like image 38
lee Avatar answered Nov 26 '22 08:11

lee