0

我有 3 个表需要加入,即表发票项目付款。表格项目付款将根据发票 ID加入表格发票

现在我需要按发票日期获得销售额、成本后销售额和付款总和。

所以这是我的查询

SELECT SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost, SUM(PAY.amount) as paymentReceived
FROM tbl_inv B LEFT JOIN tbl_item I ON B.id = I.id_invoice 
LEFT JOIN tbl_payment PAY ON B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01'
GROUP BY B.id,b.dateInv;

结果会像这样返回

totalSales  salesAfterCost  paymentReceived
 75.540000    67.540000        622.8000

但是,当我检查此查询以获取总付款时,它将返回不同的值。

SELECT SUM(PAY.amount) paymentReceived
FROM tbl_inv B LEFT JOIN tbl_payment PAY ON B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01';

结果 :

paymentReceived
155.7000

并查询销售

SELECT SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost
FROM tbl_inv B LEFT JOIN tbl_item I ON B.id = I.id_invoice
WHERE B.dateInv = '2013-04-01';

结果 :

totalSales  salesAfterCost
37.770000   33.770000

我该如何解决这个问题?

4

1 回答 1

4

SUM()s 移动到子查询中 - 目前,付款中的每一行都与发票中的每一行相匹配,从而产生笛卡尔连接

SELECT I.totalSales,I.salesAfterCost, PAY.paymentReceived
FROM tbl_inv B
LEFT JOIN (
   select id_invoice,SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,
       SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost
  from tbl_item group by id_invoice) I
      ON
         B.id = I.id_invoice 
LEFT JOIN (
    select id_invoice,SUM(amount) as paymentReceived
    from tbl_payment group by id_invoice) PAY
       ON
         B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01'
于 2013-05-01T07:10:21.413 回答