Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUM of only TOP 10 rows

Tags:

sql

sum

top-n

I have a query where I am only selecting the TOP 10 rows, but I have a SUM function in there that is still taking the sum of all the rows (disregarding the TOP 10). How do I get the total of only the top 10 rows? Here is my SUM function :

SUM( fact.Purchase_Total_Amount) Total
like image 393
Cfw412 Avatar asked Feb 12 '15 14:02

Cfw412


People also ask

How do I sum each row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

How do I add a previous row value in SQL?

1) You can use MAX or MIN along with OVER clause and add extra condition to it. The extra condition is "ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING" which will fetch previous row value. Check this: SELECT *,MIN(JoiningDate) OVER (ORDER BY JoiningDate ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS EndDate.


2 Answers

Have you tried to use something like this:

SELECT SUM(Whatever)
FROM (
    SELECT TOP(10) Whatever
    FROM TableName
) AS T
like image 124
Maciej Los Avatar answered Sep 18 '22 17:09

Maciej Los


Use the TOP feature with a nested query

SELECT SUM(innerTable.Purchase_Total_Amount) FROM
(SELECT TOP 10 Purchase_Total_Amount FROM Table) as innerTable
like image 35
LCIII Avatar answered Sep 19 '22 17:09

LCIII