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
.
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.
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.
The SUM() function returns the total sum of a numeric column.
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.
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()
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