问题描述
select distinct
opch.docentry as 'AP Invoice #',pch1.linenum as 'AP Invoice Line #',pch1.itemcode as 'Item Code',pch1.dscription as 'Item Name',pch1.freetxt as 'Free Text',pch1.priceafvat as 'Gross Price',pch1.quantity as 'Quantity',pch1.gtotal as 'Gross Total'
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
opdn on opdn.docentry = pch1.basedocnum
inner join
pdn1 on opdn.docentry = pdn1.docentry
inner join
opor on opor.docentry = pdn1.basedocnum
inner join
por1 on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
order by
opch.docentry
这是我试过的总和语句
select
opch.docentry,sum(pch1.gtotal)
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
opdn on opdn.docentry = pch1.basedocnum
inner join
pdn1 on opdn.docentry = pdn1.docentry
inner join
opor on opor.docentry = pdn1.basedocnum
inner join
por1 on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
group by
opch.docentry,opdn.docstatus
但是它不会返回正确的数量,因为它根据连接的表格复制了一些答案。
就我做错的地方请求帮助。
*更新 这是选择不同查询的结果 enter image description here
我的目标是 sum 查询来对 pch1.gtotal 列的结果求和
谢谢。
解决方法
问题在于您在发票和交货单之间进行的连接。你没有加入这条线,所以它会乘以结果。正确的连接是使用 BaseEntry、BaseLine 和 BaseType 完成的。这同样适用于与采购订单的连接。
select
opch.docentry,sum(pch1.gtotal)
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
pdn1 on pdn1.docentry = pch1.baseentry and pdn1.linenum = pch1.baseline and pdn1.objtype = pch1.basetype
inner join
opdn on opdn.docentry = pdn1.docentry
inner join
por1 on por1.docentry = pdn1.baseentry and por1.linenum = pdn1.baseline and por1.objtype = pdn1.basetype
inner join
opor on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
group by
opch.docentry