sqlalchemy: get max/min/avg values from a table - python

I have this query:
mps = (
session.query(mps) .filter_by(idc = int(c.idc))
.filter_by(idmp = int(m.idmp))
.group_by(func.day(mps.tschecked))
).all()
My problem is, that I don't know how to extract (with sqlalchemy) the max/min/avg value from a table...
I find this: Database-Independent MAX() Function in SQLAlchemy
But I don't know where to use this func.max/min/avg...
Can someone tell me how to do this? Can you give me an example?

The following functions are available with from sqlalchemy import func:
func.min
func.max
func.avg
Documentation is available here.
You can use them i.e. in the query() method.
Example:
session.query(self.stats.c.ID, func.max(self.stats.c.STA_DATE))
(just like you use aggregate functions in plain SQL)

Or just use an order_by() and select the first or last element. . .

Related

How to create SQL Pypika Query with "Min()"

I am trying to create a Pypika Query which uses the MIN('') function of SQL. Pypika supports the function but I don't know how to use it.
Basically I want to create this SQL statement in Pypika:
select
"ID","Car","Road","House"
from "thingsTable"
where "ID" not in
(
select MIN("ID")
from "thingsTable"
GROUP BY
"Car","Road","House"
)
order by "ID"
I have tried something like this:
from pypika import Query, Table, Field, Function
query = Query.from_(table).select(min(table.ID)).groupby(table.Car, table.Road, table.House)
And variations of it, but can't figure out how to use this function. There are not a lot of examples around.
Thanks in advance.
Try this one
the code based on Selecting Data with pypika
from pypika import functions as fn
tbl = Table('thingsTable')
q = Query.from_(tbl).where(
tbl.ID.isin(tbl.groupby(tbl.Car, tbl.Road, tbl.House).select(fn.Min(tbl.Id)))
).select(
tbl.Id,tbl.Car,tbl.House,tbl.Road
).orderby(tbl.Id)

What is the equivalent of python 'in' but for sqlalchemy

I have a dictionary that is being used to query the database for a match. I have one single query line that isn't working for me. If i have a list like this:
user['names']= [Alice, Bob, John]
Since this is a list I tried to use something like this:
q.filter(UserTable.firstname in user['firstnames'])
But for whatever reason this doesn't work. However, I know that Bob is in the database. When I manually pull down all the queries I can see the name is there in one of the rows. If I do this instead:
q.filter(UserTable.firstname == user['firstnames'][1]) #Only does Bob
It works. And when I pull all the queries manually, convert each row to a dictionary, and then do a
row[#row_that_matches].firstname in user['names']
that also works. But for some reason using the "in" keyword in sqlalchemy doesn't work as expected. Does anyone know an alternative that can make an sqlalchemy query for something in a list of values?
Use the in_() column method to test a column against a sequence:
q.filter(UserTable.firstname.in_(user['firstnames'])
See the Common Filter Operations section of the Object Relational tutorial:
IN:
query.filter(User.name.in_(['ed', 'wendy', 'jack']))
# works with query objects too:
query.filter(User.name.in_(
session.query(User.name).filter(User.name.like('%ed%'))
))

How to replace columns in sqlalchemy query

I have the query:
q = Session.query(func.array_agg(Order.col))
The compiled query will be:
SELECT array_agg(order.col) FROM orders
I want dynamically replace the existing column. After replacing query have to be:
SELECT group_concat(orders.col) FROM orders
I have to use Session and model. I don't have to use SQLAlchemy core. I don't have to use subqueries. And, of course, there can be some other columns, but I need to replace only one. I tried to replace objects in column_descriptions property, I tried to use q.selectable.replace (or something like this, sorry, but I don't remember right names) and I didn't get right result.
The right method:
q = Session.query(func.array_agg(Order.col))
q.with_entities(func.group_concat(Order.col))
SELECT group_concat(orders.col) FROM orders

How to get peewee result length

I use peewee orm in python.
I have a query that :
userOrganizations = (UserOrganization
.select(UserOrganization,Organization)
.join(Organization)
.where(UserOrganization.user==user.user_id)
.aggregate_rows()
)
I want to get length of userOrganizations variable. Is there any method like userOrganizations.length() ?
According to the peewee documentation you can use the count() function, i.e.:
userOrganizations.count()
If you're worried about maybe running extra DB queries, you can convert your result to a list and get the length, like:
len(list(userOrganizations))
Source for second technique: this question.

Retreive max/min possible values for an Integer column [duplicate]

I have this query:
mps = (
session.query(mps) .filter_by(idc = int(c.idc))
.filter_by(idmp = int(m.idmp))
.group_by(func.day(mps.tschecked))
).all()
My problem is, that I don't know how to extract (with sqlalchemy) the max/min/avg value from a table...
I find this: Database-Independent MAX() Function in SQLAlchemy
But I don't know where to use this func.max/min/avg...
Can someone tell me how to do this? Can you give me an example?
The following functions are available with from sqlalchemy import func:
func.min
func.max
func.avg
Documentation is available here.
You can use them i.e. in the query() method.
Example:
session.query(self.stats.c.ID, func.max(self.stats.c.STA_DATE))
(just like you use aggregate functions in plain SQL)
Or just use an order_by() and select the first or last element. . .

Categories

Resources