I'm working on a query that return a result set divided in groups, I want to get the summation of column "MA" with the last value of column "DATE" in each group, All of my attempts are resulting in wrong summation and wrong last value.
This one of my attempts: here when I do ORDER BY "DATE" in the ROW_NUMBER() it get different results, I can't do ORDER BY another column because its useless unless I used ROW_NUMBER() in ORDER BY and this is impossible.
WITH cte AS
(
SELECT
SUM([ADB_LAST].[MA]) AS [MA],
SUM([ADB_LAST].[DA]) AS [DA],
[ADB_LAST].[ID_BAS],
[ADB_LAST].[PRO_NUMBER],
[ADB_LAST].[ACC_NUMBER],
[ADB_LAST].[DATA], [ADB_LAST].[DATE] AS MyDate,
[ADB_LAST].[Q],
[ADB_LAST].[P],
RNum = ROW_NUMBER() OVER (PARTITION BY [ADB_LAST].[ACC_NUMBER] ORDER BY [ADB_LAST].[DATE] DESC),
[ADB_LAST].[UNIT],
[ADB_LAST].[ID],
SUM([ADB_LAST].[R]) AS [R]
FROM
[ADB_LAST](@PRO_NAME, @SDAY, @FDAY)
GROUP BY
[ACC_NUMBER], [PRO_NUMBER], [DATA], [Q], [P],
[UNIT], [ID], [ID_BAS], [DATE]
HAVING
SUM([R]) <> 0
)
SELECT
MA, DA,
[ID_BAS],
[PRO_NUMBER],
[ACC_NUMBER],
[DATA],
[Date],
[Q], [P],
[UNIT],
[ID],
R
FROM
cte
WHERE
RNum = 1
I've asked a similar question before and the answer solved my problem at that time but this time with the expected results it's not going as I wish.
Here is a screenshot of the result in which column "MA" has correct summation values but column "DATE" has wrong values, the date of first row must be 27/01/2008 which is the DATE value of the last row in the result of the previous query.