Group by & count function in sqlalchemy
The documentation on counting says that for group_by
queries it is better to use func.count()
:
from sqlalchemy import func
session.query(Table.column,
func.count(Table.column)).group_by(Table.column).all()
group by and count in sqlalchemy
You need to use a subquery to count the cities per country and than select the max from count of the subquery:
subq = select(hotel.c.country,
hotel.c.city,
func.count(hotel.c.city)
.label('count'))\
.group_by(hotel.c.country,
hotel.c.city)\
.subquery()
stmt = select(subq.c.city,
subq.c.count)\
.having(func.max(subq.c.count))\
.group_by(subq.c.country)
print(session.execute(stmt).all())
SQLAlchemy with count, group_by and order_by using the ORM
I've found the best way to do this. Simply supply a from_statement
instead of a filter_by
or some such. Like so:
meta.Session.query(Location).from_statement(query).all()
sqlalchemy group_by and count
You are right - you cannot do it using query_property
because it implicitely selects the whole object (all attributes of it), so adding the group_by
would not produce the desired result because undesired columns are included in the non-aggregate part of the query.
However you can simply use a db_session.query([Person.country, ...]).group_by(...)
. So all you need to do is to add db_session
property to the Person
class along with query
and then use it to create a desired query explicitely:
class Person(object):
session = db_session
query = db_session.query_property()
....
How to access count value as dict/property in sqlalchemy with group_by?
Found the answer to my question after re-reading the official ORM tutorial
All I need to do is to set a label for the column for which there's no corresponding property in my class.
So, instead of doing this:
servers = session.query(func.count(Server.type), Server.type).group_by(Server.type).all()
I should do that:
servers = session.query(func.count(Server.type).label('total_count'), Server.type).group_by(Server.type).all()
Then I can access the total_count
property (provided by the label
function):
for server in servers:
print(server.type, server.total_count)
Multiple group_by counts on single table using SQLAlchemy
Is straight SQL can use the FILTER clause on count to get the individual city counts with standard count to for the total: See example here
select name, total, ny, chi, la
from ( select name
, count(*) total
, COUNT(*) FILTER (WHERE city='Chicago') chi
, COUNT(*) FILTER (WHERE city='Los Angeles') la
, COUNT(*) FILTER (WHERE city='New York') ny
from users
group by name
) sq;
I leave it to you to convert to SQLAlchemy; since I can read it to understand, but am not comfortable attempting writing it.
Related Topics
Extract a Page from a PDF as a Jpeg
How to Parse a Website Using Selenium and Beautifulsoup in Python
How to Decorate an Instance Method with a Decorator Class
How to Bind a List to a Parameter in a Custom Query in SQLalchemy
What Is :: (Double Colon) in Python When Subscripting Sequences
Listing Available Com Ports with Python
Parsing HTML in Python - Lxml or Beautifulsoup? Which of These Is Better for What Kinds of Purposes
How to Find Out If Python Is Compiled with Ucs-2 or Ucs-4
Return String with First Match for a Regex, Handling Case Where There Is No Match
Vectorised Haversine Formula with a Pandas Dataframe
Sorting by a Custom List in Pandas
Importing from a Relative Path in Python
Removing Unicode \U2026 Like Characters in a String in Python2.7
Board-Drawing Code to Move an Oval
Pyplot Common Axes Labels for Subplots
How to Perform HTML Decoding/Encoding Using Python/Django
How to Force Python to Be 32-Bit on Snow Leopard and Other 32-Bit/64-Bit Questions