Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum over a field on a query

this should be a asked-before question, I searched but I could not find any answer on that. Sorry if it is duplicated. I have a query lets say:

my_query=session.query(Item).filter(somefilter)

Now, Item has a column, lets say counter, and I want to find the sum of this column of my_query. I can do that like this:

sum=0
for row in query:
    sum+=row.counter

but I don't this this is the efficient way of doing this specially in a large database. I know that this is possible: sqlalchemy simple example of `sum`, `average`, `min`, `max`, but this requires filtering on qry (borrowed from the page) which I have already given the filtered version my_query. I dont know if it is really more efficient to do the filtering again on top of qry v.s. using the for loop on my_query.

like image 781
Amin Avatar asked Jan 16 '13 03:01

Amin


People also ask

How do you sum a query in Excel?

If you need to sum a column or row of numbers, let Excel do the math for you. Select a cell next to the numbers you want to sum, click AutoSum on the Home tab, press Enter, and you're done. When you click AutoSum, Excel automatically enters a formula (that uses the SUM function) to sum the numbers.

How do I total a column in Access query?

On the Home tab, in the Records group, click Totals. For each cell in the Total row where you want a total to appear, click in the cell and select the kind of total you want.

How do I sum a specific column in SQL?

The SUM() function returns the total sum of a numeric column.

How do you sum a calculated field in an Access report?

In the Navigation Pane, right-click the report and then click Layout View. Click the field you want to summarize. For example, if you want to add a total to a column of numbers, click one of the numbers in the column. On the Design tab, in the Grouping & Totals group, click Totals.


1 Answers

I had the same question. I asked on irc.freenode.org#sqlalchemy and inklesspen pointed me to Query#with_entities().

sum = my_query.with_entities(func.sum(Item.counter)).scalar()
like image 145
Nick Retallack Avatar answered Sep 22 '22 05:09

Nick Retallack