为了账号安全,请及时绑定邮箱和手机立即绑定

使用SQLAlchemy计算结果集中包含的值的实例

使用SQLAlchemy计算结果集中包含的值的实例

拉丁的传说 2021-05-07 18:20:01
如果问题标题不是描述性的/措辞不当,则表示歉意。我希望能够计算出在满足特定条件的行中有多少个特定值的实例。考虑以下两个表,queues以及queue_contents队列表:+----+---------+| id |  name   |+----+---------+|  1 | queue A ||  2 | queue B ||  3 | queue C |+----+---------+queue_contents表:+-----+----------+--------+| id  | queue_id | foo_id |+-----+----------+--------+|  1  |        1 |    10  ||  2  |        1 |    11  ||  3  |        1 |    12  ||  5  |        2 |    20  ||  6  |        2 |    21  ||  7  |        2 |    23  ||  8  |        2 |    24  ||  9  |        3 |    10  ||  10 |        3 |    11  ||  11 |        3 |    20  ||  12 |        3 |    30  |+-----+----------+--------+我想要一个查询,当我查询时输出以下结果 queue_id == 3+----------+------------+-------------+-----------------------+| queue_id | queue_name | total_count | contained_in_this_one |+----------+------------+-------------+-----------------------+|        1 | queue A    |           3 |                     2 ||        2 | queue B    |           4 |                     1 |+----------+------------+-------------+-----------------------+我不知道如何计算foo_id发生在queue_contents.foo_id WHERE queue_contents.queue_id == 3total_count对于每个队列来说,获取它都是微不足道的,但是当涉及到设置子查询和条件时,我感到很困惑。我觉得该解决方案涉及使用子查询并计算该子查询foo_id中出现的s的数量,但我无法使其正常工作。我不会包括我尝试过的以下查询的maaaany迭代,尽管这可以使您大致了解我所处的轨道:foo_id此查询中的ssq = db_session.query(Foo.id.label('foo_id')) \               .join(QueueContent, QueueContent.foo_id == Foo.id) \               .filter(QueueContent.queue_id == 3) \               .subquery('sq')foo_alias = aliased(Foo)q2 = db_session.query(func.count(Foo.id).label('total_in_task'),                      func.count(foo_alias.id).label('count_in_this_task'),                      Queue.id.label('queue_id'),                      Queue.name.label('queue_name')) \             .join(foo_alias, foo_alias.id == Foo.id) \             .join(QueueContent, QueueContent.foo_id == Foo.id) \             .join(Queue, Queue.id == QueueContent.queue_id) \             .filter(Queue.id != 3) \             .group_by('queue_name', 'queue_id')
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号