I have a query that returns a result fairly quickly:
SELECT [Date],[AccountCode],[ModelCode],[Generic],SUM([MTMusd]) AS 'MTMusd'
FROM [dbo].[MTM]
WHERE [AccountCode] = 'XXX'
AND [ModelCode] = '1'
GROUP BY [Date],[AccountCode],[ModelCode],[Generic]
ORDER BY [Date]
CREATE TABLE [dbo].[MTM](
[AccountCode] [nvarchar](50) NULL,
[ModelCode] [nvarchar](50) NULL,
[Date] [date] NULL,
[TIMESTAMP] [time](7) NOT NULL,
[Generic] [nvarchar](50) NULL,
[MTMUsd] [float] NOT NULL
) ON [PRIMARY]
However, I don't want SUM()
I want LAST()
.
In the GROUP BY I have missed out [TIMESTAMP]
which is the time of day. I want my query to return the record with the LAST TIMESTAMP
for each GROUP { [Date],[AccountCode],[ModelCode],[Generic]
}
How can I achieve this efficiently? I have approx 5 millions rows.
I tried ROW_NUMBER() OVER ()
based example I found, but processing took an order of minutes.