从具有条件的多个表中获取SUM()

时间:2014-02-04 11:12:29

标签: mysql sql aggregate-functions

我试图从两张表中获取due_amount,即发票和offline_invoice。
条件是; status not like 'paid%'。我正在使用此查询

select 
    (sum(i.total_amount) + sum(oi.invoice_amount)) - (sum(i.paid_amount) + sum(oi.paid_amount)) due_amount
from
    {CI}invoices i
        left join
    {CI}offline_invoice oi ON oi.customer_id = i.customer_id
where
    i.customer_id = ?
        and i.status not like 'paid%'
group by i.customer_id

但我不知道如何在连接表上使用条件({CI} offline_invoice)?我必须使用相同的条件(status not like 'paid%')。

1 个答案:

答案 0 :(得分:1)

只需添加and到ON子句

   left join
    {CI}offline_invoice oi ON oi.customer_id = i.customer_id
       AND oi.status not like 'paid%'
where
    i.customer_id = ?
        and i.status not like 'paid%'

但是,如果没有可能的笛卡尔影响,我不确定这对你有用。假设您有10张当前发票和10张和6张离线发票。我会根据客户ID加入两个单独的预聚合...除非离线发票具有与当前相同的发票ID(例如存档目的)

select 
      CurInvoices.Customer_ID,
      CurInvoices.InvBalance + COALESCE( OIInvoices.OIBalance, 0 ) as AllBalanceDue
   from
      ( select i.customer_id,
               sum( i.total_amount - i.paid_amount ) as invBalance
           from
              {CI}invoices i
           where
                  i.customer_id = ?
              and i.status not like 'paid%'
           group by
              i.customer_ID ) as CurInvoices
      LEFT JOIN 
      ( select oi.customer_id,
               sum( oi.total_amount - oi.paid_amount ) as OIBalance
           from
              {CI}offline_invoice oi
           where
                  oi.customer_id = ?
              and oi.status not like 'paid%' 
           group by
              i.customer_ID ) as OIInvoces
         on CurInvoices.Customer_ID = OIInvoices.customer_ID