0

我有几张桌子:

Invoice
-----------------
ID        total     
1         500.00
2         100.00
3          10.00

Payment
---------------------------------------
ID    invoiceId     Amount   Method
1        1           400       CASH
2        2            60       CASH
3        2            40      CREDIT

我需要一个查询来获取所有发票,其中至少一个 payment.method 是 CREDIT 并且该发票的所有付款的总和大于发票的总和。

我需要它快。

我怎样才能做到这一点?

4

3 回答 3

1

Another method:

SELECT
  i.`id`,
  i.`total` AS `total_invoiced`,
  SUM(p.`amount`) AS `total_payments`,
  SUM(IF(p.`method`='credit', 1, 0)) AS `count_credit`
FROM `invoices` i
LEFT JOIN `payments` p ON (p.`invoice_id`=i.`id`)
WHERE 1=1
GROUP BY i.`id`
HAVING (`total_payments` > i.`total`) AND (`count_credit` > 0)

I changed some table/field names. Sorry for the inconvenience.

http://www.sqlfiddle.com/#!2/7402d/1/0

于 2013-04-11T23:51:11.033 回答
1
SELECT  a.ID InvoiceID,
        a.Total TotalInvoice, 
        b.TotalPayment
FROM    Invoice a
        INNER JOIN
        (
            SELECT  InvoiceID, SUM(Amount) TotalPayment
            FROM    Payment
            GROUP   BY InvoiceID
            HAVING  SUM(Method = 'CREDIT') > 0
        ) b ON a.ID = b.InvoiceID AND
                a.Total < b.TotalPayment
于 2013-04-11T23:39:47.600 回答
0

试试这个:

    select iagg.ID 
      from (
                select i.ID
                     , sum (p.amount)   tl_paid
                     , min (i.total)    tl
                  from invoice  i
                  join payment  p   on  ( p.invoiceID = i.ID )
              group by i.ID
           )  iagg
     where exists (
                select 1
                  from payment p2
                 where p2.invoiceId = iagg.ID
                   and p2.method    = 'CREDIT'
           )
       and iagg.tl_paid > iagg.tl
         ;

属性上的最小值运算符total由分组运算符规定,最小值实际上取自一组相同的值。

于 2013-04-11T23:39:02.660 回答