当我加入taxdetails表时,从ItemDetails表得到了错误的TotalPrice。
代码1:select Distinct B.ID as BillId, I.ID as ItemDetailId, I.TotalPrice as ItemPrice, T.Amount as TaxAmount from Bill B inner join ItemDetails I on I.BillNoID = B.ID inner join TaxDetails T on T.ItemDetailId = I.Id;
参考下图,
当对同一个查询的TotalPrice和TotalTaxAmount求和时,我得到了一个错误的TotalPrice结果,
代码2:select Distinct B.ID as BillId, SUM(I.TotalPrice) as TotalPrice, SUM(T.Amount) as TotalTaxAmount from Bill B inner join ItemDetails I on I.BillNoID = B.ID inner join TaxDetails T on T.ItemDetailId = I.Id group by B.ID;
请参考下图,
实际问题是根据taxdetails per itemdetail每行的行数变为多行,因此totalprice get不同。
代码2的预期输出(我已经列出了第一行预期结果)是,
Billid TotalPrice TotalTaxAmount总税金额
1970年30月
最佳答案
试试这个,您有多个项目/帐单,这就是为什么您不能直接进行内部联接。还可以删除group by。
select B.ID as BillId,
I.TotalPrice as TotalPrice,
T.Amount as TotalTaxAmount from Bill B
inner join
(
select BillNoID,SUM(TotalPrice) as TotalPrice from ItemDetails
group by BillNoID
)as I on I.BillNoID = B.ID
inner join
(
Select ItemDetailId,SUM(Amount) as Amount from TaxDetails
group by ItemDetailId
)as T on T.ItemDetailId = I.Id
关于mysql - 在MYSQL中使用内部联接时获取总金额的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22602860/