如果问题标题不是描述性的/措辞不当,则表示歉意。我希望能够计算出在满足特定条件的行中有多少个特定值的实例。考虑以下两个表,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')
添加回答
举报
0/150
提交
取消