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

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
carl
  • 4,216
  • 9
  • 55
  • 103

1 Answers1

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()
van
  • 74,297
  • 13
  • 168
  • 171