如果问题标题不具有描述性/措辞不当,请道歉。你知道吗
我希望能够计算满足特定条件的行中出现的特定值的实例数。考虑以下两个表,queues
和queue_contents
队列表:
+----+---------+
| id | name |
+----+---------+
| 1 | queue A |
| 2 | queue B |
| 3 | queue C |
+----+---------+
队列内容表:
+-----+----------+--------+
| 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 |
+----------+------------+-------------+-----------------------+
我不知道如何统计发生在queue_contents.foo_id WHERE queue_contents.queue_id == 3
中的foo_id
实例
为每个队列获取total_count
已经足够简单了,但是当涉及到设置子查询和条件时,我就被难住了。我觉得解决方案需要使用一个子查询并计算该子查询中出现的foo_id
个数,但我无法让它工作。我不会包含我尝试过的以下查询的任何迭代,尽管这会让您了解我所处的轨道:
foo_id
在这个查询中sq = 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')
如果
queue_id
组不包含foo_id
个重复项,则可以使用左联接:如果是这样,则可以使用包装在NULLIF中的EXISTS子查询表达式(或转换为整数并求和):
这两种变体都使用这样一个事实:COUNT(expression)生成expression的值不为空的行数。你知道吗
相关问题 更多 >
编程相关推荐