2

I am new to sql alchemy and I would like to count unique rows in my table and output the unique rows together with the number of copies for that row. Lets assume I have a table like this

Table A
--------------
id
address

now I want to get all rows of this table but for rows with the same adress I want to get only one row (doesn't matter which id). I also want to know how many ids are at a particular address. So if there are two people living at the same address "main street" (lets say id=4 and id =12) I would like to get an output like this ("main street", 2),

Here is my starting attempt

query = models.A.query
query = query.add_columns(func.count(models.A.address)).all()

this however, gives me the total number of rows in that table. So I guess func.count is the wrong function? thanks in advance carl

1 Answer 1

5

count is the right function, but you need to specify groups of what you would like to count. Below should do it:

q = (session.query(A.address, func.count(A.id).label("# people"))
    .group_by(A.address)
     ).all()
Sign up to request clarification or add additional context in comments.

1 Comment

Importing func is as simple as this: from sqlalchemy import func

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.