首页 > 解决方案 > Sqlalchemy 将 2 个查询组合成单个查询,来自同一个表的公共列

问题描述

我想将 2 个查询合并为一个:qa 和 qs。在对列求和时,每个查询本身都会给出正确的结果。当这两者结合在一起时,总和列没有正确相加。我尝试了几种分组和使用 func.sum 的方法

一个查询是可用数量:

qa = Alltitles.query.join(Partnames, Partnames.id == Alltitles.partname_id) \
            .join(Modelnumbers, Modelnumbers.id == Alltitles.modelnumber_id) \
            .add_columns(Modelnumbers.modelnumber,
                         Partnames.partname,
                         func.sum(Alltitles.quantityavailable - Alltitles.quantitysold))\
            .group_by(Alltitles.modelnumber_id, Alltitles.partname_id)\
            .order_by(Modelnumbers.modelnumber, Partnames.partname)

示例输出行:

qa: (<Alltitles 486501>, 'H737Q2', 'Resistor', 6) # correct quantity available

另一个查询是销售数量:

qs = Alltitles.query.join(Partnames, Partnames.id == Alltitles.partname_id) \
        .join(Modelnumbers, Modelnumbers.id == Alltitles.modelnumber_id) \
        .outerjoin(Allsoldrecords, Allsoldrecords.title_id == Alltitles.id) \
        .add_columns(Modelnumbers.modelnumber,
                     Partnames.partname,
                     func.sum(Allsoldrecords.quantity))\
        .group_by(Alltitles.modelnumber_id, Alltitles.partname_id)\
        .order_by(Modelnumbers.modelnumber, Partnames.partname)

示例输出行:

qs: (<Alltitles 486364>, 'H737Q2', 'Resistor', 16)  # correct quantity sold

将我尝试过的两者结合起来::

qaqs = Alltitles.query.join(Partnames, Partnames.id ==Alltitles.partname_id) \
            .join(Modelnumbers, Modelnumbers.id == Alltitles.modelnumber_id) \
            .join(Allsoldrecords, Allsoldrecords.title_id == Alltitles.id)\
            .add_columns(Modelnumbers.modelnumber,
                         Partnames.partname,
                         func.sum(Alltitles.quantityavailable),
                         func.sum(Alltitles.quantitysold),
                         (Alltitles.quantityavailable - Alltitles.quantitysold),
                         func.sum(Allsoldrecords.quantity))\
            .group_by(Alltitles.modelnumber_id, Alltitles.partname_id)\
            .order_by(Modelnumbers.modelnumber, Partnames.partname)

示例输出行:

both (<Alltitles 486364>, 'H737Q2', 'Resistor', 85, 72, 13, 16)

使用:

func.sum(Alltitles.quantityavailable),
                                 func.sum(Alltitles.quantitysold),

示例输出行:

both: (<Alltitles 486364>, 'H737Q2', 'Resistor', 11, 8, 3, 16)

使用:

Alltitles.quantityavailable,
                         Alltitles.quantitysold,

将这两个查询组合到“qaqs”会为 Alltitles.quantityavailable 和 Alltitles.quantitysold 生成不正确的结果,但在查询“qa”和“qs”中是正确的。这里最好的解决方案是什么?

标签: pythonsqlsqlitesqlalchemy

解决方案


推荐阅读