Questions tagged [sum]

The result of adding two or more quantities together.

The sum or total refers to the result of a summation operation. To refer to the operation yields a sum, use the [tag: addition] tag. A summation involves adding two or more numbers or other quantities. It is primarily an arithmetic operation which means it deals with numbers and also other mathematical objects. However, sum can be used in other contexts which may not necessarily be a result of a mathematical operation. Almost all programming languages support addition of numbers using the + operator. Most programming languages support the summation operation through a built-in language construct or as a utility function part of the standard library.


Examples of sum in various programming languages

C++

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> array{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = std::accumulate(array.begin(), array.end(), 0, std::plus<int>());
    std::cout << sum;
    return 0;
}

Python:

sum_of_items = sum([1, 2, 3, 4, 5, 6])
# sum_of_items will be equal to 21

SQL

SELECT SUM(column1) FROM MyTable
WHERE column1 = "condition"

C#

List<int> array = new List<int>() {1, 2, 3, 4, 5};
int sum = array.Sum();  # sum == 21

Java

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      var numbers = Arrays.asList(1, 2, 3, 4, 5);
      var sum = numbers.stream().mapToInt(Integer::intValue).sum();
      System.out.println(sum);
    }
}

R

x <- c(1.1, 2.5, -0.4)
y <- c(NA, 1.7)
sum(x)
sum(y)
sum(y, na.rm = TRUE)
sum(x, y)  ## as same as sum(c(x, y))
sum(x, y, na.rm = TRUE)  ## as same as sum(c(x, y), na.rm = TRUE)
15351 questions
101
votes
5 answers

How to sum data.frame column values?

I have a data frame with several columns; some numeric and some character. How to compute the sum of a specific column? I’ve googled for this and I see numerous functions (sum, cumsum, rowsum, rowSums, colSums, aggregate, apply) but I can’t make…
User
  • 62,498
  • 72
  • 186
  • 247
92
votes
7 answers

Summing elements in a list

Here is my code, I need to sum an undefined number of elements in the list. How to do this? l = raw_input() l = l.split(' ') l.pop(0) My input: 3 5 4 9 After input I delete first element via l.pop(0). After .split(' ') my list is ['5', '4', '9']…
treng
  • 1,665
  • 3
  • 15
  • 22
84
votes
8 answers

How do I add two count(*) results together on two different tables?

I have two tables: Toys and Games. +--------------------+------------------+ | Field | Type | +--------------------+------------------+ | toy_id | int(10) unsigned | | little_kid_id | int(10) unsigned…
Runcible
  • 7,006
  • 12
  • 42
  • 62
83
votes
2 answers

Sum range of int's in List

I reckon this will be quite trivial but I can't work out how to do it. I have a List and I want to sum a range of the numbers. Say my list is: var list = new List() { 1, 2, 3, 4 }; How would I get the sum of the first 3 objects? The…
Bali C
  • 30,582
  • 35
  • 123
  • 152
81
votes
3 answers

Using GroupBy, Count and Sum in LINQ Lambda Expressions

I have a collection of boxes with the properties weight, volume and owner. I want to use LINQ to get a summarized list (by owner) of the box information e.g. **Owner, Boxes, Total Weight, Total Volume** Jim, 5, 1430.00, 3.65 George,…
Jimbo
  • 22,379
  • 42
  • 117
  • 159
79
votes
9 answers

Get sum of two columns in one LINQ query

let's say that I have a table called Items (ID int, Done int, Total int) I can do it by two queries: int total = m.Items.Sum(p=>p.Total) int done = m.Items.Sum(p=>p.Done) But I'd like to do it in one query, something like this: var x = from p in…
Axarydax
  • 16,353
  • 21
  • 92
  • 151
74
votes
14 answers

Linq query with nullable sum

from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points).Sum() } I got this query, however it fails if no votes are found with…
AndreasN
  • 2,881
  • 3
  • 24
  • 29
73
votes
1 answer

Sum of items in a collection

Using LINQ to SQL, I have an Order class with a collection of OrderDetails. The Order Details has a property called LineTotal which gets Qnty x ItemPrice. I know how to do a new LINQ query of the database to find the order total, but as I already…
Adrian
  • 1,147
  • 1
  • 10
  • 13
72
votes
8 answers

How can I change NULL to 0 when getting a single value from a SQL function?

I have a query that counts the price of all items between two dates. Here is the select statement: SELECT SUM(Price) AS TotalPrice FROM Inventory WHERE (DateAdded BETWEEN @StartDate AND @EndDate) You can assume all of the tables have been set up…
Matt
  • 5,249
  • 12
  • 40
  • 45
65
votes
2 answers

How can I count how many duplicates there are for each distinct value in sqlite?

I have a table: ref,type 1,red 2,red 3,green 4,blue 5,black 6,black I want the result of a sqlite query to be: red,2 green,1 blue,1 black,2 I think the hardest thing to do is find a question to match my problem? Then I am sure the answer is…
Chris Denman
  • 1,187
  • 3
  • 9
  • 15
64
votes
5 answers

How to select sum -or- 0 if no records exist?

I need to write a query that returns the sum of all values that meet a certain criteria, but the query needs to return 0 if no rows are found, rather than null. For example: tab +---------------+-----+ | descr | num…
ewok
  • 20,148
  • 51
  • 149
  • 254
64
votes
2 answers

MYSQL Sum Query with IF Condition

I am building a query for a report with multiple IF conditions on the SUM. I am having problems with a multiple IF conditions on the SUM. Here is the query: SELECT SUM(`totalamount`) AS Total, SUM(`PayPalFee`) AS Fees, DATE(`TransactionDate`) AS…
Matthew Colley
  • 10,816
  • 9
  • 43
  • 63
62
votes
8 answers

Counting positive integer elements in a list with Python list comprehensions

I have a list of integers and I need to count how many of them are > 0. I'm currently doing it with a list comprehension that looks like this: sum([1 for x in frequencies if x > 0]) It seems like a decent comprehension but I don't really like the…
fairfieldt
  • 861
  • 1
  • 6
  • 10
62
votes
7 answers

Finding moving average from data points in Python

I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fine, but in the exercise it says: Modify your…
dingo_d
  • 11,160
  • 11
  • 73
  • 132
61
votes
5 answers

Sum one number to every element in a list (or array) in Python

Here I go with my basic questions again, but please bear with me. In Matlab, is fairly simple to add a number to elements in a list: a = [1,1,1,1,1] b = a + 1 b then is [2,2,2,2,2] In python this doesn't seem to work, at least on a list. Is there a…
Leon palafox
  • 2,675
  • 6
  • 27
  • 35