1

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ä
  • 45,748
  • 6
  • 100
  • 105
carl
  • 3,900
  • 7
  • 39
  • 93

1 Answers1

4

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
  • 68,849
  • 11
  • 156
  • 163