FAQ Database Discussion Community

## Extracting raster values, from maximum, to cumulatively sum to x

r,sum,raster
I am trying to determine the location of raster cells that add up to a given amount, starting with the maximum value and progressing down. Eg, my raster of 150,000 cells has a total sum value of 52,000,000; raster1 <- raster("myvalues.asc") cellStats(raster1,sum) = 52,000,000 I can extract the cells above...

## sum of Digits through Recursion

java,function,recursion,sum,digit
I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

## SQL COUNT And SUM

sql,count,sum,base,libreoffice
I have a table having this table done_by Var_ID| Var_name| Q1_by |Q2_by|Q3_by|Q4_by 1 | abc | me | me |me |you 2 | cba | me | me |you |you 3 | abd | me | you |you |me the result i want to get is get all the total...

## How do I find the sum of every X rows in a matrix in Matlab

matlab,sum,submatrix
I have a 189 x 4914 matrix and am trying to find the sum of each row in each 1x26 sub-matrix. How would I go about this? Many thanks. ...

## comprare aggregate sum function to number in postgres

postgresql,sum,case
I have the next query which does not work: UPDATE item SET popularity= (CASE WHEN (select SUM(io.quantity) from item i NATURAL JOIN itemorder io GROUP BY io.item_id) > 3 THEN TRUE ELSE FALSE END); Here I want to compare each line of inner SELECT SUM value with 3 and update...

## sum up cells in matrix according to different hierarchical level

r,matrix,sum
I am using R to make a heatmap from binary interactions. The matrix looks as following 9 401 562 68 71 569 700 9 0 1 0 0 0 0 1 401 0 0 1 0 0 na 1 562 0 1 0 1 1 0 1 68 1 1...

## Efficient way to sum overlapping date intervals with several groupings in PostgreSQL version 8.4

sql,postgresql,group-by,sum
Hello I'm new to stackoverflow and relatively new to psql so please be lenient if I do things wrong. I have a large data set showing animal movements that looks a little like this: animalid | movementdate | offmovementdate | location | rsk ========================================================== 1 | 1998-01-01 | 1998-04-01 |...

## Select left 10 numbers, left join for a price from second table, and then sum, SQL

sql,select,sql-server-2012,sum,multiplying
I am currently working in sql 2012 visual management studio. I have two tables. Table1 has three columns (ItemNumber as varchar, Quantity as int, and TimeOrdered as datetime). Table2 has 2 columns (ItemNumber as varchar, and Price as float). Please note these item numbers are not the same, the part...

## How to sum items from csv files from a for loop

python,loops,csv,sum
I am stuck. My script asks for how many csv files a user wants to enter and by what field. In this case lets say two csv files each with a area value. I am trying to sum up the two items with a for loop so i can then...

## How to SUM() each row into another column

sql,oracle,sum,running-total
I have this table | ID_prim | ID (FKey) | Date | Moved Items | |:-----------|:------------|-------------:|:------------:| | 1003 | 12_1 | nov 2013 | 2 | | 1003 | 12_2 | okt 2013 | 3 | | 1003 | 12_3 | dec 2014 | 5 | | 1003 | 12_4...

## Query to sum the previous values

sql,oracle,sum,running-total
I have the table strucure as in the image. I need to get the values added to the sum of previous values(shown in the REQUIRED RESULT) I tried with the following query SELECT empid, sum(tot_hours) OVER (PARTITION BY empid ORDER BY empid ) AS tot_hours FROM empDet ORDER BY empid...

## C# remove item from list of integers int[] l = {1,2,3} - or use recursion to add them

c#,list,recursion,integer,sum
So there's this blog that gives Five programming problems every Software Engineer should be able to solve in less than 1 hour and I'm just revisiting some of the concepts. The first question reads Write three functions that compute the sum of the numbers in a given list using a...

## MySQL select sum then two grouping

php,mysql,sum,where,having
I have a table with id, name, type, price, name, date and type_2. Theses are bills. What do I have to query if I want to select all the bills between First May and 6 june that are to Mr. X. My code so far: SELECT sum(prix) from notes_de_frais WHERE...

## java8 stream grouping aggregate

sum,java-8,grouping,java-stream
Given a java class Something class Something { String parent; String parentName; String child; Date at; int noThings; Something(String parent, String parentName, String child, Date at, int noThings) { this.parent = parent; this.parentName = parentName; this.child = child; this.at = at; this.noThings = noThings; } String getParent() { return parent;...

## Select organizations that their income represent around 60% of the total income SQL Server2008

sql-server,sum,data-warehouse,percentage
In advance, I apologize for imperfect English In this data warehouse, we have organization which composed of multiple Organizations, I have [FactFinance] table which has information about the income of each organization. I have the following query in data warehouse which select the (Organization Name) from the [organization dimension table]...

## SQL Server - cumulative sum on overlapping data - getting date that sum reaches a given value

sql-server,sql-server-2005,sum,overlapping
In our company, our clients perform various activities that we log in different tables - Interview attendance, Course Attendance, and other general activities. I have a database view that unions data from all of these tables giving us the ActivityView that looks like this. As you can see some activities...

## PHP compare 2 arrays (Mac donalds and Burger King)

php,html,checkbox,sum,comparison
I have to make a comparison site for the products from MC and BK. http://informaticaphp.net84.net/home.php <- that's how far I am. This is the code : <html> <head> <link rel="stylesheet" type="text/css" href="style1.css" /> </head> <?php if(isset($_POST['formSubmit'])) {$breakfastMC = $_POST['BreakfastMC'];$breakfastBK = $_POST['BreakfastBK']; if(empty($breakfastMC)) { echo("<p>You didn't select any food.</p>\n");...

## Sum, Avg, Max, Min, Count of NULL values

mysql,sql,null,sum
In MySQL SELECT 2+NULL FROM tbl_name will return NULL, since MySQL cannot interpret NULL as a number. But why will SELECT SUM(quantity) FROM tbl_name not return NULL if just one of the values is NULL? The same goes for MIN, MAX, AVG, etc. Since MySQL doesn't know what NULL could...

## SQL SUM count of parents with active children

mysql,sql,select,sum
'SUM(IF(children.status > 0, 1, 0)) AS count' I currently have the above code in my select statement, however it returns the count of children who are active, rather than the amount of parents who have active children. While a large portion of my data is single children elements, there are...

## Programmatically calc sum of rows in Excel

excel,sum,rows
From the above screenshot, I'm trying to add multiple rows into the F column from cells C and D. I have manually done some of them myself, ex: Cell F2 is =SUM(C2+D2), Cell F3 is =SUM(C3+D3) Is there a way to copy this sum forumla and increment it for...

## How come the data types aren't passing through in this Haskell code?

Trying to learn Haskell. solve :: Int -> Int -> [Int] -> [Int] -> [Double] solve l r a b = [sumfunc(l,r,a,b)] sumfunc :: Int -> Int -> [Int] -> [Int] -> Double sumfunc l r a b = sum([0.001 | x <- [1000*l..1000*r]]) Trying to return the contents of...

## Scala: How to compute the sum of all elements in the leaves of a Binary Tree?

scala,sum,binary-tree,immutability,case-class
I'm learning Scala by working the exercises from the book "Scala for the Impatient". Given the following way to model binary trees with case classes, one question asks to compute the sum of all elements in the leaves. sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class...

## Expression can not contain lambda expression Linq

c#,linq,lambda,sum
I have data-table and i am trying to find sum of columns where Id starts with Particular value.I have tried some ways but getting error. result=Convert.ToInt32(dtNew.Compute("Sum(ResPending)", "Substring(ID,0,1)='G'"));//error shows-- Substring() argument is out of range And tried this way also dtNew.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));//Expression can not contain lambda expression ...

## Subquery aggregate function with SUM(CASE SUBQUERY)

sql,sql-server,sum,subquery,aggregate-functions
I'm getting an error while executing my query Cannot perform an aggregate function on an expression containing an aggregate or a subquery. Code: SELECT S.id, SUM(CASE WHEN sc.coverage IN (SELECT number FROM ArrayOfIntegersFromString(@dynamicData)) THEN 1 ELSE 0 END) as sm FROM Storefronts s LEFT JOIN StorefrontCoverages sc ON s.id =...

## Calculate the sum of time column in PostgreSql

postgresql,sum
Can anyone suggest me, the easiest way to find summation of time field in POSTGRESQL. i just find a solution for MYSQL but i need the POSTGRESQL version. MYSQL: calculate sum time with mysql SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(timespent))) FROM myTable; Demo Data id time 1 1:23:23 2 4:00:23 3 9:23:23 Desired Output...

jsp,sum,el

## Finding a number that is sum of two other numbers in a sorted array

arrays,sorting,find,sum
As it said in the topic, I have to check if there is a number that is the sum of two other numbers in a sorted array. In first part of the question (for a unsorted array) I wrote a solution, just doing 3 loops and checking all the combinations....

## mysql: order -> limit -> sum… possible?

mysql,group-by,sum,sql-order-by,sql-limit
i am loosing it over the following problem: i have a table with participants and points. each participant can have up to 11 point entries of which i only want the sum of the top 6. in this example lets say we want the top 2 of 3 +----+---------------+--------+ |...

## data.table sum and subset

r,sum,filtering,data.table
I have a data.table that I am wanting to aggregate library(data.table) dt1 <- data.table(year=c("2001","2001","2001","2002","2002","2002","2002"), group=c("a","a","b","a","a","b","b"), amt=c(20,40,20,35,30,28,19)) I am wanting to sum the amt by year and group and then filter where the summed amt for any given group is greater than 100. I've got the data.table sum nailed. dt1[, sum(amt),by=list(year,group)]...

## Scala sum of all elements in the leaves of a tree using pattern matching

scala,tree,sum,pattern-matching,case-statement
I'm learning Scala by working the exercises from the book "Scala for the Impatient". One of the questions asks: /** * Q5: One can use lists to model trees that store values only in the leaves. For example, the list ((3, 8) 2 (5)) * describes the tree * ....

## Java Add Numbers In String

java,arrays,string,sum,substring
I'm creating an application which will take an image as input and use tesseract and give an output. This image has numbers (can vary the numbers) I'm getting an output of, (when i run on the image) 0 1 12 1 0 I'm currently getting 5which is 0+1+1+2+1+0 cause im...

## SUBTRACT two columns SUM, then SUBTRACT the result and SUM the result to show minimum quantity

mysql,count,group-by,sum
Is a little complicated the question, but I need to show the SUM of SUBTRACT two columns SUM and then SUBTRACT the result. Right now I have the result (1,1,1) when the minimum quantity is below of "x" value for each product but right now show me three buttons(because there...

## SQL Update with a Group by Statement not working

sql-server,join,group-by,sum,sql-update
I've got two temp tables. In table @due_cte I have a series of Customer_Ids, followed by payment amounts collected throughout various points in the code. The @work table has a lot of various columns including hist_amt_due. What I want to do is update @work with the amt_due from @due_cte but...

## Combine multiple dataframes into one that sums their values according to the index

python,pandas,sum
I have several pandas dataframes, each with one column of ints in them, and I would like to create a new dataframe with the sum of their values at each index. Their indexes will have some overlapping entries and these are the indecies whose values I want to add together....

## R - passing variable containing column name into sum()

r,variables,sum
Let's say we've attached a data from a table containing column 'banana' with numeric values. colName='banana' Now we want the sum of that column, assuming we don't know what it's called, we only know the name is being stored in the colName variable. How do we call the sum() function?...

## SUM query, between dates, grouped by employee

sql-server-2012,sum,aggregate
I have 4 tables, structured as follows: More verbosely, a project consists of a set of tasks. An employee can add one or more notes to the database, specifying the amount of time spent on that task on any given date. I would like to find for each employee, how...

## Exact sum of a long array

java,sum,integer-arithmetic
In order to get the exact sum of a long[] I'm using the following snippet. public static BigInteger sum(long[] a) { long low = 0; long high = 0; for (final long x : a) { low += (x & 0xFFFF_FFFFL); high += (x >> 32); } return BigInteger.valueOf(high).shiftLeft(32).add(BigInteger.valueOf(low)); }...

## How to know which checkbox are selected if I have a number with the sum of all values checked?

c#,checkbox,sum
I have an existing database, and my table has a field in which is stored a value, a sum of all "values" of my checkbox list. Another programmer made this method, called it "logic sum". I don't know this method, but now I need to know the reverse method, so...

## Working with sums in R

r,sum
How does one work with sums in R? I can't seem to find an easy way to calculate sums \sum_{i=m}^n a_i. There are three things to decide here; where summation starts, where it ends, and what elements are to be summed. I have a data frame df and I would...

## Trying to create a new dataframe based on internal sums of a column from another dataframe using Python/pandas

python,indexing,pandas,sum,dataframes
Let's assume I have a pandas dataframe df as follow: df = DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]}) Col1 Col2 0 1 5 1 2 6 2 3 7 3 4 8 Is there a way for me to change a column into the sum of all the following elements in the column? For...

## SQL select sum/average all rows

sql-server,select,sum,average
i have this code who picks rows from table, but i need to make him return sum of all rows or avg of all rows. I tried to put code in other select like select within sum(select), but its not working, any ideas how to make it work? Sorry for...

## How to Call JavaScript functions by clicking a button and perform operations in looped textboxes?

javascript,php,mysql,sum
I'm new in javascript and I want to know how to perform some math operations per row in the table by clicking the button. The textboxes in the column "Variable" are created by a while loop, and I want to iterate the operation over two values one value from the...

## How to perform convolution using Fourier Series

matlab,sum,continuous-integration,convolution,fourier-descriptors
OK let me cut to the chase. I am trying to use MATLAB to (i)generate the fourier series based on known coefficients and thereafter (ii) determine the output function when the impulse is known. So far I used this code to obtain the fourier series: clear all syms x k...

## EXCEL SUM cells which contain string

string,excel,search,sum,formula
I'm trying to write a formula in Excel which will run down a column, and search each cell in that column for the presence of a string (which may be in the middle of another string); if the string is found, move over to another column and add the value...

## SUM() Function not Working in sqLite

sqlite,select,group-by,sum
We have a table that is like this: Customer ItemNumber Item_Name Qty FOCQty C1 I1 ABC 10 2 C2 I2 BCA 12 2 C3 I1 ABC 3 3 C4 I2 BCA 05 1 But we want it to be like this: ItemNumber Item_Name Qty FOCQty I1 ABC 13 5 I2...

## how to sum a field from 3 tables and display the results together

sql-server,select,sum
im using sql server and I have 3 tables called accnt, acc1152, and acc1167. each of these tables has an amnt field and a accno field with a few thousand records in it. i need to sum the entire amnt column for acc1152 and acc1167, then sum the amnt column...

## VBA to sum payments for a specific person and set the sum in a merged cell

excel,vba,excel-vba,sum
I have a very large excel file, around 50K rows. In Column (C) I have the person numbers 1,1,1,1,2,3,4,5,.... and in Column(N) I have the payments for this person, so the data looks like What I want is to sum All payments for one person from column N and set...

## R - Compute increments for use in power variation

r,sum,binomial-coefficients
I am working with high frequent data, which is a vector X of decimal numbers. I would like to code the following in R, but am at complete loss where to start: n decides how big intervals we are looking at. This can be any value, this is not so...

## Count the maximum amount of numbers in an array which sum is an even number

java,arrays,performance,sum
I have this code, which, as I understand it, searches for the maximum amount of consecutive numbers in the given array, which sum is an even number. private static int f (int[]a, int low, int high) { int res = 0; for (int i=low; i<=high; i++) res += a[i]; return...

## Sum of all subparts of an array of integers

arrays,algorithm,sum,big-o,subset
Given an array {1,3,5,7}, its subparts are defined as {1357,135,137,157,357,13,15,17,35,37,57,1,3,5,7}. I have to find the sum of all these numbers in the new array. In this case sum comes out to be 2333. Please help me find a solution in O(n). My O(n^2) solution times out. link to the problem...

## Excel formula: Sum if two columns match

excel,if-statement,sum,excel-formula,sumifs
I need a formula that only sums numbers in a cell from a column if it matches two cells in the same row. In J3 i'm trying to get the sum of all the returns that are from January 2009. In J4 'm trying to get the sum of all...

## summing from two tables then preforming an operation with the 2 sums

sql-server,insert,sum,sql-update
I am using sql server and I have a table called accnt with the fields ven1 and amnt1 and a table called acc1167 with fields ven, job#, and amnt. for this example these tables look like this accnt acc1167 ven1 amnt1 ven job# amnt 1167 100 1167 1 200 1152...

## How to Calculate Aggregated Product Function in SQL Server

sql,sql-server,sum,aggregate-functions,exp
I have a table with 2 column: No. Name Serial 1 Tom 1 2 Bob 5 3 Don 3 4 Jim 6 I want to add a column whose a content is multiply Serial column like this: No. Name Serial Multiply 1 Tom 2 2 2 Bob 5 10 3...

## Dynamical SUMIF command

excel,sum,condition
If it is possible, I'd like to create a formula that will allow me the following: Formula must be in the entire column or in this example, in the range B1:B5. The formula is based on a condition, that when the total sum of cells from column A is lower...

## How can I use target address to get sum of a range of cells? [closed]

excel,vba,sum,range,target
I have target.address (or just target) from a worksheet_change sub. I'd like to use the row from target.address and a range of columns (H:W), and get a sum of that range. So, for instance, if I have $100 in H10 and I add$50 in J10, I'd like to get...

## fn:sum error “cannot cast to xs:double”

xpath,casting,sum,xquery
I'm trying to add up multiple nodes (names & amount of nodes uncertain). performing the query for $x in //onboard/* return$x returns this (and more) <total> <one/> </total> <total> <one>124</one> <two>1</two> <three>0</three> </total> <total> <one>46</one> </total> <total> <one>129</one> <two>1</two> <three>0</three> </total> <seafarers> <one>149</one> <two>3</two>...

## For loop - 2 arrays

javascript,arrays,for-loop,sum
I'm a beginner and I've been stuck for hours. I have problems with a simple for loop. I want an alert box that gives me the sum of the bars controlled by the player (it's part of the code for a simple boardgame) This is my code: var districts =...

## Dsum Function in Query Field not working properly

ms-access,sum,ms-access-2010,ms-access-2013,running-total
I have a date based query that returns two fields, Week Ending Date and L2N, and I want to add a third field that provides a rolling total of the L2N field. I have tried using DSum as follows: RunL2N: DSum("[L2N]","Occupied Apts & L2N", "Week Ending Date=" & "'" &...

## VBA SUM Variable Range

excel,vba,variables,sum,range
I want a code to sum the Variable rows up if certain condition is met. e.g. If A12 is numeric and B12 is empty then insert a fomula in cell C12 to sum C3:C11. Then perform the same action at C22 and C30. The problem I have is don't...

## Is this working properly - Sum of Fibonacci in Python 3

python,numbers,sum,fibonacci
I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also. Input: 10 Output: 89 ----------- Input: 100 Output: 573147844013817084101 Is it correct...

## Sum a value in SSRS Reports based on date range

date,reporting-services,sum,range
I'm trying to sum a field value in an SSRS report based on a date range field in the same dataset, but have had no luck. So far this is what I've come up with. I've scoured the forums with no luck. Any help would be greatly appreciated. = sum(...

## Translating mathematical functions from MATLAB to Python

python,matlab,numpy,sum,sign
I am currently working on a project which involves translating a program which runs in MATLAB to Python to increase speed and efficiency. However, I have hit a stumbling block. First, I am confused as to what the tilde(~) indicates in MATLAB, and how to represent that in a corresponding...

## SQL: Query to merge (some) rows

sql,oracle,merge,sum,group
I'm currently trying to create a query that merges some rows to one category and sums up the related values. I'll try to illustrate it with the following example: Country | Sales Jan | Sales Feb | Sales Mar --------+-----------+-----------+---------- Austria | 100 | 110 | 120 Spain | 120...

## Correlated subqueries: How to get the ID of the outer query?

sql,sum,subquery,correlated-subquery
I have multiple tables : Person --------------------- IDPerson, Name StickerTransaction --------------------- IDTransac, IDPerson, IDSomeoneElse, NbStickersReceived, NbStickersGiven Purchase --------------------- IDPurchase, IDPerson, NbStickersBought I'm trying to get every person who never made a transaction or currently have 0 sticker. To have the number of stickers a person has, here's the formula :...

## SUM previous value in php

php,mysql,sum
How can I create a function which can SUM the previous row with the new row and show me the result per each row?. Like this in the column"SALDO": | Cantidad | nombre del producto | Precio compra | Precio DNM | Precio venta | Total compra | Saldo |...

## Percentage for each result where id = id

php,html,for-loop,mysqli,sum
In my database i have a table wich looks like this: Now, in my php code i make a SUM like this: function number_of_axless() { $sql = "SELECT (sum(distance))/(25000)*(100) as totaldistance1 FROM axle WHERE train_id = :train_id";$sth = $this->pdo->prepare($sql); $sth->bindParam(':train_id',$_GET['train_id'], PDO::PARAM_STR); $sth->execute(); return$sth->fetchAll(); } And: <?php \$number_of_axles...

## I am trying to sum probes count within subgroup of a dataframe in R [duplicate]

r,sum
This question already has an answer here: Idiomatic R code for partitioning a vector by an index and performing an operation on that partition 3 answers I am biochemistry student working with breast cancer data (Copy number probes). I have the following data frames for primary breast tumors: Patient...