sum over a field on a query - sqlalchemy

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.

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()

There is a whole bunch of SQL "group" functions in sqlalchemy.func:
from sqlalchemy import func
my_query = session.query(func.sum(Item.counter)).filter(somefilter)

Related

Select a sum in Knex.js without using .raw

I am trying to rewrite some MySQL queries in Knex.js, and I feel like I'm running into .raw at every turn, which feels counter to the reason I want to use Knex in the first place.
Is it possible to write the following query without using .raw?
SELECT
product,
SUM(revenue)
FROM orders
Using raw, it works to write:
knex()
.select(
'product',
knex.raw('SUM(revenue)')
)
.from('orders')
but the idea of using Knex was to avoid using MySQL query strings, so I'm hoping there's another way. Or does everyone just use .raw everywhere, and I'm misunderstanding something? Very possible, I'm new to this.
You can use the sum method.
sum — .sum(column|columns|raw) Retrieve the sum of the values of a
given column or array of columns (note that some drivers do not
support multiple columns). Also accepts raw expressions.
knex('users').sum('products')
Outputs:
select sum("products") from "users"
Probably be something like this:
knex()
.select('product')
.sum('revenue')
.from('orders')
You should adjust to your specific case. You might need to use something like groupBy('product') to get total revenue per product.
You should really go over knex's documentation, it's pretty good and straight forward and you definitely should not be using raw all the time.
You can even specify the returning sum column name like this:
knex(tableName)
.select('product')
.sum({ total: 'revenue' })
.groupBy('product');

How to select the cases which were in the same day within 2 datetime type variables

I have a quick question about the mysql query.
Let's suppose I have two columns which are both datetime type vairables, one is start_at, another one is end_at.
And I want to choose all of the cases which start and end in the same day. How can I do that?
I am thinking the queries like this:
where year(start_at) = year(end_at)
and month(start_at) = month(end_at)
and day(start_at) = day(end_at);
And I am trying to find a better way to approach that goal. Any clue guys?
Much more simply:
where date(start_at) = date(end_at)

Access query amazing

When I do that on access, SELECT RMonturesImp.N°Fac
FROM RMonturesImp, Rpartielun
WHERE NOT (RMonturesImp.N°Fac IN (1,2,5))
GROUP BY RMonturesImp.N°Fac;
but when I do this
SELECT RMonturesImp.N°Fac
FROM RMonturesImp, Rpartielun
WHERE NOT (RMonturesImp.N°Fac IN Requête2)
GROUP BY RMonturesImp.N°Fac;
it doesn't work (it shows 1,2,5 indeed) although the result of Requête2 (which is a query) is also (1,2,5). I can't understand this!
Thanks in advance
It's quite easy. The IN (1,2,5)) must be explicit as SQL will not evaluate an expression not to say a function to obtain the values for IN.
So build your SQL in code creating the string, or pull the values from a (temp) table.
Try this:
SELECT RMonturesImp.N°Fac
FROM RMonturesImp, Rpartielun
WHERE RMonturesImp.N°Fac NOT IN (Select N°Fac From Requête2)
GROUP BY RMonturesImp.N°Fac;

Using results in one query to use in another query - Orace MySql

I want to be able to use the results of the first query and place into the second query, sorry if this doesn't make much sense, im new to all of this.
First Query
SELECT "NAME", "TYPE","CATEGORY" "Meters" FROM BBT_Locations
WHERE SQRT(Power((:myLocX-LOCX), 2) + Power((:MyLocY - LOCY),2)) < :Distance;
Second Query
Select Round((:Distance/20)*4)as "Meters";
Can you please elaborate more as in which field value of 1st query you would like to use in 2nd query ? There are JOIN query and Sub query concept in SQL which can be used. But we should know the field that we would like to use and get value for, based on that we can select the kind of query to write.

nested "select " query in mysql

hi i am executing nested "select" query in mysql .
the query is
SELECT `btitle` FROM `backlog` WHERE `bid` in (SELECT `abacklog_id` FROM `asprint` WHERE `aid`=184 )
I am not getting expected answer by the above query. If I execute:
SELECT abacklog_id FROM asprint WHERE aid=184
separately
I will get abacklog_id as 42,43,44,45;
So if again I execute:
SELECT `btitle` FROM `backlog` WHERE `bid` in(42,43,44,45)
I will get btitle as scrum1 scrum2 scrum3 msoffice
But if I combine those queries I will get only scrum1 remaining 3 atitle will not get.
You Can Try As Like Following...
SELECT `age_backlog`.`ab_title` FROM `age_backlog` LEFT JOIN `age_sprint` ON `age_backlog`.`ab_id` = `age_sprint`.`as_backlog_id` WHERE `age_sprint`.`as_id` = 184
By using this query you will get result with loop . You will be able to get all result with same by place with comma separated by using IMPLODE function ..
May it will be helpful for you... If you get any error , Please inform me...
What you did is to store comma separated values in age_sprint.as_backlog_id, right?
Your query actually becomes
SELECT `ab_title` FROM `age_backlog` WHERE `ab_id` IN ('42,43,44,45')
Note the ' in the IN() function. You don't get separate numbers, you get one string.
Now, when you do
SELECT CAST('42,43,44,45' AS SIGNED)
which basically is the implicit cast MySQL does, the result is 42. That's why you just get scrum1 as result.
You can search for dozens of answers to this problem here on SO.
You should never ever store comma separated values in a database. It violates the first normal form. In most cases databases are in third normal form or BCNF or even higher. Lower normal forms are just used in some special cases to get the most performance, usually for reporting issues. Not for actually working with data. You want 1 row for every as_backlog_id.
Again, your primary goal should be to get a better database design, not to write some crazy functions to get each comma separated number out of the field.