python - 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”中是正确的。这里最好的解决方案是什么?
解决方案
推荐阅读
- java - Android studio java - 在视图寻呼机内的地图片段中显示底部工作表行为
- java - Maven 依赖网络 - NoSuchMethodError
- javascript - 琐事 游戏构建快完成了,如何检查用户的猜测并返回真实的交叉引用对象索引?
- java - 生成的 Jhipster War 似乎不适用于 6.3.1(独立和 tomcat)
- javascript - 如何在jquery中获取动态表数据中文本框的值
- react-native - 在使用 Firebase 身份验证的 Expo 反应本机应用程序中添加“使用 Apple 登录”
- sql - 选择 * 不返回任何结果
- javascript - 在 AngularJS ng-repeat 中过滤“自定义值”
- inno-setup - 根据使用 IDP 首次下载的内容下载其他文件
- javascript - 控制台日志未从构造函数打印