I have a SQL Server Compact database with two tables:
- Consumers
- Monthly Bills
Each month's bill is stored in the monthly bill table, I want to get consumers with the last month bill stored in the monthly bill table. I have tried the following query, but I'm not getting the expected result.
SELECT TOP 1
CM.id,
MM.BillMonth,
SUM(MM.AfterDuePayable) AS AfterDuePayable
FROM
MonthlyBills MM
LEFT JOIN
Cosumers CM ON MM.ConsumerCode = CM.id
WHERE
CM.isActive = 0
AND MM.AfterDuePayable > 0
GROUP BY
CM.id, MM.BillMonth
ORDER BY
CM.id,
DATEPART(Month, MM.BillMonth),
DATEPART(Year, MM.BillMonth) DESC
Tables:
This is the result I get:
ID BillMonth AfterDuePayable
--------------------------------------
30 2023-01-02 5710
Expected result is:
ID BillMonth AfterDuePayable
-------------------------------------
1 2023-01-02 400
2 2023-05-06 350
3 2022-05-08 340