Assuming your table looks like this
CREATE TABLE invoices (
-- ...some stuff ...
client_id ...,
due_date date ,
amount_due ...,
-- ... some more stuff ...
)
Try this:
SELECT client_id,
DATEDIFF(CURDATE(), due_date) AS days_past_due,
SUM(IF(days_past_due = 0, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 1 AND 30, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 31 AND 60, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 61 AND 90, amount_due, 0)),
SUM(IF(days_past_due > 90, amount_due, 0))
FROM invoices
GROUP BY client_id
John Douthat
2009-05-07 19:28:22