Question

I am having a hard time listing all the clients for which no invoice has been created in the last 6 weeks.Two tables are involved, client and invoice. My current query looks like this:

select MAX(invoice.created_date) 'Last Invoice Date', invoice.invoice_no 'Invoice No.', DATEDIFF(curdate(), max(invoice.created_date)) 'Days since last invoice created', client.name 'Client'  
from invoice 
left join
client on invoice.client_id = client.id 
where 
datediff (curdate(), (select MAX(invoice.created_date) from invoice left join client on invoice.client_id = client.id)) >  42
group by client.id;

But it returns an empty set. Any help would be appreciated

Was it helpful?

Solution

Starting the join from invoice means that straight away any clients with no invoices are excluded. You can start from client and join onto invoice to get the information you need in the select and then use an EXISTS clause to only grab clients with no invoice in the last x days:

SELECT MAX(invoice.created_date) 'Last Invoice Date', invoice.invoice_no 'Invoice No.', DATEDIFF(curdate(), max(invoice.created_date)) 'Days since last invoice created', client.name 'Client'  
FROM client c
LEFT JOIN invoice i ON (i.client_id = c.id)
WHERE NOT EXISTS(
    SELECT 1 FROM invoice i2
    WHERE i2.client_id = c.id
    AND DATE_SUB(NOW(), INTERVAL 42 DAY) < i2.created_date
)
GROUP BY c.id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top