Unable to get last entry from SQL Server Compact Edition Database Through Group By And Order By Functions

54 views Asked by At

I have a SQL Server Compact database with two tables:

  1. Consumers
  2. 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:

Database 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
0

There are 0 answers