SQLAlchemy-计数状态为true [英] SQLAlchemy - count status is true

查看:101
本文介绍了SQLAlchemy-计数状态为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在db中有两个表。一个被命名为company,另一个被命名为company_map。
公司表格,例如:

I have two tables in db. One is named company, the other named company_map. company table like:

C_ID NAME  Contact
1    a     12334   
2    b     12335
3    c     12336
4    d     12337
5    e     12338

company_map像这样的表:

company_map table like:

M_ID C_ID  STATUS
1     1     True   
2     1     False
3     1     True
4     3     True
5     3     True

我需要计算数字在C_ID分组的company_map表中,哪个状态为true。例如,我需要获取C_ID的数量为1,并且其STATUS为true,应该为2。现在我可以获取C_ID的数量,通过使用func.count(company_map.C_ID),它将获得3。如何计算状态== true()?我尝试了一些方法,但是没有用。

I need to count the number which STATUS is true in the company_map table, group by the C_ID. For example, I need to get the number of C_ID is 1 and its STATUS is true, it should be 2. I can get the number of C_ID now, by use func.count(company_map.C_ID), it will get 3. But how to count STATUS == true()? I try some method, but none is work.

推荐答案

我从布尔列上的SQLAlchemy func.count

.having(func.count(case([(company_map.STATUS, 1)])) < func.count(company_map.C_ID)) 

如果您的SQLAlchemy是最新版本,则可以使用

If your SQLAlchemy is latest version, can use

.having(func.count(1).filter(company_map.STATUS))

旧的。

这篇关于SQLAlchemy-计数状态为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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