count unique rows in sql-alchemy

亡梦爱人 提交于 2020-01-03 05:45:08

问题


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:


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()


来源:https://stackoverflow.com/questions/31863255/count-unique-rows-in-sql-alchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!