Question

I have two tables like invoices and receipts

1. invoices

    id name    amt   status
    1   test    100   paid
    2   test1   300  not paid
    3   test2   400  not paid

2. receipts
    id amount invoice_id receipt_date
     1  50      1         22-apr-2014  
     2  30      1         24-apr-2014   
     3  30      1         25-apr-2014

Following is my query

@invoices_info = Invoice.select("invoices.id as inv_id,receipts.receipt_date as receipt_date,sum(receipts.amount) as receipt_amount")
                      .joins('left join receipts on receipts.invoice_id = invoices.id')
                      .where("invoices.status in ('Paid')")
                      .group("invoices.id").order("receipts.receipt_date desc")

This query shows data as:
 inv_id  receipt_amount receipt_date
   1      100            22-apr-2014

So problem is, it fetch first date rather than descending date. I want last receipt date "25-apr-2014".

Can anyone help me?

Was it helpful?

Solution

Your Invoice.select() doesn't map to valid SQL. Valid SQL requires every unaggregated column in the SELECT clause to also appear in the GROUP BY clause. MySQL's "extension" to GROUP BY, which allows what you did, is not deterministic. (MySQL is giving you whatever date is easiest for it to fetch.) SQL developers regard this as a bug, not a feature.

I'll use SQL for the rest of this answer.

Executing this SQL statement in PostgreSQL . . .

select invoices.id as inv_id, receipts.receipt_date as receipt_date, sum(receipts.amount) as receipt_amount
from invoices
left join receipts on receipts.invoice_id = invoices.id
where invoices.status in ('paid')
group by invoices.id, receipts.receipt_date
order by receipts.receipt_date desc

returns this output.

1   2014-04-24   30
1   2014-04-22   80

If you want only the sum per invoice, which makes more sense, you can use a much simpler SQL query.

select invoice_id, sum(amount)
from receipts
group by invoice_id;

1    110

If you want the sum and the date of the latest receipt . . .

select invoice_id, max(receipt_date), sum(amount)
from receipts
group by invoice_id;

1   2014-04-24   110
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top