Blankman
Blankman

Reputation: 267200

How can I sum the last 15 rows in my database table?

I have a Sales table, with the following columns:

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?

Upvotes: 0

Views: 384

Answers (2)

Eoin Campbell
Eoin Campbell

Reputation: 44308

SELECT Sum(amount )
FROM
(
   SELECT Top 15 amount FROM Sales ORDER BY [Date] Desc
) as bar

Upvotes: 3

gbn
gbn

Reputation: 432511

SELECT
    SUM (Amount)
FROM
    (SELECT TOP 15 amount FROM Sales ORDER BY [Date] DESC) foo

Upvotes: 10

Related Questions