Mysql双加入SUM发票总额和付款

时间:2013-07-25 13:54:41

标签: mysql sql zend-framework

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

我离开时加入了发票上的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张发票付款时。付款计算两次。我怎么能只让它算一次?

1 个答案:

答案 0 :(得分:0)

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

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

另请查看this question