计算sql-alchemy中的唯一行 [英] count unique rows in sql-alchemy

查看:67
本文介绍了计算sql-alchemy中的唯一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是sql alchemy的新手,我想统计表中的唯一行,并输出唯一行以及该行的副本数. 假设我有一个这样的表

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

现在我想获取该表的所有行,但是对于地址相同的行,我只希望获取一行(与哪个id无关).我也想知道在一个特定的地址上有多少个ID. 因此,如果有两个人住在同一地址主要街道"(假设id = 4和id = 12),我希望得到这样的输出(主要街道",2),

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

这是我的开始尝试

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

但是,这给了我该表中的总行数.所以我猜func.count是错误的函数? 提前致谢 卡尔

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

推荐答案

count是正确的功能,但是您需要指定要计数的.在下面应该做到这一点:

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

这篇关于计算sql-alchemy中的唯一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆