How can I sum the last 15 rows in my database table?
-
05-09-2019 - |
Question
I have a Sales table, with the following columns:
- employeeID
- amount
- date
Now I want to SUM
up the last 15 rows, so I am currently doing:
SELECT TOP 15 SUM(amount) FROM Sales ORDER BY [Date] DESC
But I get 15 rows obviously, is there a way I can sum it up and not have to loop through and SUM it on the client side?
Solution
SELECT
SUM (Amount)
FROM
(SELECT TOP 15 amount FROM Sales ORDER BY [Date] DESC) foo
OTHER TIPS
SELECT Sum(amount )
FROM
(
SELECT Top 15 amount FROM Sales ORDER BY [Date] Desc
) as bar
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow