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

2024-09-28 20:56:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如果问题标题不具有描述性/措辞不当,请道歉。你知道吗

我希望能够计算满足特定条件的行中出现的特定值的实例数。考虑以下两个表,queuesqueue_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')

Tags: 实例nameinidfooqueuecountcontents
1条回答
网友
1楼 · 发布于 2024-09-28 20:56:11

如果queue_id组不包含foo_id个重复项,则可以使用左联接:

qc2 = aliased(QueueContent)

session.query(QueueContent.queue_id,
              func.count(),
              func.count(qc2.foo_id)).\
    outerjoin(qc2, and_(qc2.queue_id == 3,
                        qc2.foo_id == QueueContent.foo_id)).\
    filter(QueueContent.queue_id != 3).\
    group_by(QueueContent.queue_id)

如果是这样,则可以使用包装在NULLIF中的EXISTS子查询表达式(或转换为整数并求和):

qc2 = aliased(QueueContent)

sq = session.query(qc2).\
    filter_by(queue_id=3, foo_id=QueueContent.foo_id).\
    exists()

session.query(QueueContent.queue_id,
              func.count(),
              func.count(func.nullif(sq, False))).\
    filter(QueueContent.queue_id != 3).\
    group_by(QueueContent.queue_id)

这两种变体都使用这样一个事实:COUNT(expression)生成expression的值不为空的行数。你知道吗

相关问题 更多 >