0

我建立了一个发票系统,现在我尝试查看每张发票的总价格和要支付的金额。

我离开加入了发票上的 invoice_part 表并进行了总结,现在我也想加入付款表,但是当我总结时,有时会多次付款。有没有办法我可以完成加入只收一次付款?

$stmt->from(array('x'=>'invoice'),array('x.id as id','x.ref_id as ref_id','x.start_date as start_date','x.regard as regard','x.project_code as project_code'));
$stmt->joinLeft(array('ip'=>'invoice_part'),'x.id=ip.invoice_id','SUM(ip.price*ip.amount*(100-ip.discount)/100) as price_ex');
$stmt->joinLeft(array('p'=>'payment'),'x.id=p.invoice_id','SUM(ip.price*ip.amount*(100-ip.discount)*(100+tax)/10000)-IFNULL(SUM(p.amount),0) as price_open');
//joins the payment multiple times if there are multiple invoice parts, payment should only be joined once
//note: there can be multiple payments for one invoice
$stmt->group('x.id');

结果查询:

SELECT  `x`.`id` ,  `x`.`ref_id` ,  `x`.`start_date` ,  `x`.`regard` ,  `x`.`project_code` ,  `o`.`name` AS  `contact` ,  `d`.`name` AS  `department` ,  `c`.`name` AS  `company` ,  `is`.`name` AS  `status` , SUM( ip.price * ip.amount * ( 100 - ip.discount ) /100 ) AS  `price_ex` , SUM( ip.price * ip.amount * ( 100 - ip.discount ) * ( 100 + tax ) /10000 ) - IFNULL( SUM( p.amount ) , 0 ) AS  `price_open` 
FROM  `invoice` AS  `x` 

LEFT JOIN  `invoice_part` AS  `ip` ON x.id = ip.invoice_id
LEFT JOIN  `payment` AS  `p` ON x.id = p.invoice_id
GROUP BY  `x`.`id` 

所以当我有 2 个发票部分和 1 个发票付款时。付款被计算两次。我怎么能只算一次呢?

4

1 回答 1

0

您可以将总和除以重复次数,如下所示:

SUM(tbl.field_to_sum) / COUNT(tbl.primary_key) * COUNT(DISTINCT tbl.primary_key)

也看看这个问题

于 2013-07-25T14:24:32.317 回答