I have a table of invoices with a unique id, invoice date and company id. The problem I'm having is that the invoice dates are only the date part and don't include time. We have some companies that have multiple invoices on the same date, so the following query returns all records for that date instead of the intended 1 latest invoice. Is it possible to also get the max id of the row to limit it to just one result per date/company? If so, how?
SELECT accountinginvoice.CompanyId, accountinginvoice.invoicedate
FROM accountinginvoice
INNER JOIN (
SELECT MAX(invoicedate) as invoicedate, companyid FROM accountinginvoice
GROUP BY companyid
) AS ai ON (accountinginvoice.invoicedate = ai.invoicedate
AND accountinginvoice.companyid = ai.companyid)
order by accountinginvoice.invoicedate
Here's an example of the results I'm getting.
id | invoicedate | companyid
1037 | 2021-01-06 00:00:00.000 | 6639
1039 | 2021-01-06 00:00:00.000 | 6639
1040 | 2021-01-06 00:00:00.000 | 6639
1045 | 2021-01-06 00:00:00.000 | 6639