FAQ Database Discussion Community


Using Sum in If in Mysql

mysql,sql,select,sum
I want to select the sum of values of my_field. The unit of my_field is in seconds. I don't want to exceed 24 hours, so when it exceeds 24 hours, I want it to select 24*60*60 = 86400. SELECT IF(SUM(my_field) > 86400, 86400, SUM(my_field)) ... This solution doesn't seem to...

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...

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...

Formula to return the sum of a range in Excel for certain rows in a different column

excel,sum,formula
I would like to use formula to return the sum of cells from column B where cell value in column A is equal to a certain week number. The table is below. For example if Week = 1 the SUM would be 40; Week = 2 SUM = 110 ,etc....

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]...

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...

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...

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 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. ...

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)]...

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>...

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(...

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;...

Getting sum using EL and JSP

jsp,sum,el
<% double sum = 0.0; %> <c:forEach var="user" items="${page.content}"> <% sum += $user.grade; %> ${user.grade} </c:forEach> I want get the sum of all user.grade. How to do it?...

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...

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...

countif and sumif each row without grouping

sql,sum,countif
I'm trying to figure out sumif and countif using SQL Here is the code to start with: SELECT ItemID , Supplier , Cost , SalePrice FROM countifExpirement I'm trying to create this output: First four columns already have data and i'm trying to create calculated fields to calculate duplicate Items,...

Python 3.x - Using the sum function to concatenate strings in a list

python,python-3.x,sum,concatenation
x= ['Good', 'morning'] # example list of strings I have to use sum(x) to concatenate both and print (x). I'm having trouble converting the list into integers for the sum function to work. >>>print (sum(x)) 'Goodmorning' ...

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...

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...

PHP, MySQL How to Sum data in two different date range

php,mysql,sum
Im having trouble doing this +------------+------------+------------+ | Name | year | Value | +------------+------------+------------+ | Name1 | 2015 | 100 | | Name1 | 2014 | 150 | | Name1 | 2013 | 200 | | Name2 | 2015 | 130 | | Name2 | 2014 | 160 | |...

Double sum and how to make a matrix to plot in 3D? (surface plot)

matlab,function,matrix,plot,sum
Edit To clarify. I have a function f that takes in 5 arguments z,x,y,n,m. The order of events should go as follows: Upon calling the function test, the variable z is assigned, say z = 1. A linear combination is created by adding f with with each of elements of...

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?...

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...

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");...

Return 0 in sum when no values to sum - sql server

sql,sql-server,sql-server-2008-r2,sum
Trying to return 0 if any of these columns have no values returned, in my particular case 'Past Due' has no values to total, so it is returned, so i get the return in the second snippet here. How can I return something if these are no values to count?...

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...

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...

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...

Multiple Datasets in one Table OR show distinct Value in Table (SSRS)

mysql,reporting-services,sum,aggregate-functions
I am fairly new to SSRS and currently I'm working on building my first reports. I encounter some problems with a report that in my opinion should be fairly easy, but so far I couln't find the right answer. I have a table similar to this: Material - - Date...

how to sum a field and distribute the sum between records in another table

sql,sql-server,select,sum
I have a table whose records consist of minor inventory. I need to sum the cost of these records and distribute the sum in another table based on the price of the record. for example. say the sum of the inventory is is $1000, and I have 4 jobs in...

SUM Column SQL SERVER

sql-server-2008,sum
I have a table in SQL Server, and I need to sum a column, like the example below: CREATE TABLE B ( ID int, Qty int, ) INSERT INTO B VALUES (1,2) INSERT INTO B VALUES (2,7) INSERT INTO B VALUES (3,2) INSERT INTO B VALUES (4,11) SELECT *, ''...

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 +----+---------------+--------+ |...

Dynamic Summing Range

excel,vba,sum,excel-2010
Currently I have a medical spread-sheet with a list of clients that we have serviced. We have 8 different clinical categories which are denoted by different acronyms - HV,SV,CV,WV,CC,OV,TS and GS. A client can receive multiple therapies i.e. HV,SV,CV - in the background we have a counter mechanism which would...

SQL Server : Sum by Row to output

sql-server,sum,row
Trying to display sum of same rows as output. Here is SQL code SELECT replace(replace(replace(replace(dbo.IDENTITY_MAP.Name,'My Company\',''),'-VLAN2',''),'.VLAN2\',''),'.Instr\','') as Site, Count (CASE WHEN dbo.SEM_AGENT.AGENT_VERSION LIKE '11.%' AND dbo.SEM_COMPUTER.OPERATION_SYSTEM LIKE 'Windows%' THEN 1 END) AS 'Windows-SEP-11', Count (CASE WHEN dbo.SEM_AGENT.AGENT_VERSION LIKE '11.%' AND dbo.SEM_COMPUTER.OPERATION_SYSTEM LIKE 'Mac%' THEN 1 END) AS 'Mac-SEP-11', Count(CASE WHEN...

Summation Run Time Analysis

performance,time,sum,analysis
A[] is size of n, B[][] is size of nxn for i_{1,n} { for j_{1,n} { if(i<=j) -> B[i,j] = sum of the elements A[i], A[i+1],...,A[j] else -> B[i,j] = 0 I understand that first 2 for loops are n iterations for both. My question is how to do if(i<=j)...

SQL query sum unique records

sql,sql-server,tsql,sum
I'm trying to sum all sales of one period of time of a selling vehicle. The problem is that every product sold is one row whit amount and price and a total of the bill and the bill number. So I have 2 options: multiply ever sold product amount whit...

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...

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...

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...

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=" & "'" &...

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...

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...

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 calculate a sum of products of array elements using a fast Fourier transform?

c++,arrays,c++11,sum,fft
I have some binary array. For example, let my array is: int a[] = {1, 0, 0, 0, 1, 0, 1, 0, 1} I want to calculate the values based on this formula: How to calculate this function, using a fast Fourier transform? I have a large array and I...

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

haskell,sum
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...

Given a sorted array and a parameter k, find the count of sum of two numbers greater than or equal to k

c++,arrays,algorithm,sum
I tried to find all pairs in the array with sum equal to k, the solution to that takes O(n*log(n)) time. Here is the code snippet - map<int,int> mymap; map<int,int>::iterator it; cin>>n>>k; for( int i = 0 ; i < n ; i++ ){ cin>>a; if( mymap.find(a) != mymap.end() )...

Group array by common id and date and sumarize to calendar table

php,arrays,date,sum,group
I've been ripping my hair out on this one. Struggling with understanding how i really want to attack this problem, even the basic logic... I've got this dataset: Array ( [0] => stdClass Object ( [id] => 233773869 [pid] => 9919304 [tid] => 6754304 [uid] => 1502708 [project] => **HIDDENNAME**...

Oracle SQL Groupby and SUM

sql,oracle,group-by,sum
I have the following query that groups every tender id and description and shows its total Sum: 3020 American Express 20 1000 Cash - primary currency 9903.25 3120 House Card 2605.56 4070 Purchase Order 668.25 3000 Visa 26005.19 SELECT B.TENDER_TYPE_ID, A.TENDER_TYPE_DESC, SUM (B.TENDER_AMT) FROM POS_TENDER_TYPE_HEAD A, SA_TRAN_TENDER B, SA_TRAN_HEAD C...

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...

Summing results of an function for each element of an array

c++,arrays,function,for-loop,sum
I want to make an array, where each element sums up the result of a function"CosineEffect". For example if the "heliostatNumber" is 3, each element in the "Cosine" array should be the sum of three results of funcion"CosineEffect". But when I print the result out, it seems that they dont...

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 ...

Ruby Update Attribute with Sum of Database Attributes

ruby-on-rails,ruby,database,attributes,sum
I have a database with three values: tips_value, profile_value, and value. For each entry in the database, whenever I update the entry, I want to take the sum of tips_value and profile_value and assign it to value, but it's not working. Here is my update function: def update @affinity =...

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...

Oracle Get sum of distinct group without subquery

sql,oracle,sum,group,partition
I already have a working example which does exactly what I need. Now the problem is, that I'm not really a fan of subqueries and I think there could be a better solution to this problem. So here is my (already) working example: with t as ( select 'Group1' as...

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...

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...

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 =...

MySQL summing verses and n biggest results

mysql,select,sum
I've a table looking more or less like that: **Day** | **Mileage** ---------------- 1 | 13 2 | 2 3 | 25 4 | 15 5 | 20 6 | 8 7 | 17 8 | 12 9 | 16 10 | 5 How to write a SQL query: Returning...

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...

excel count/sum stop count/sum match?

excel,count,sum,match,sumifs
I have tried to see if this question has been asked before, but I can't seem to find an answer. I have a column of cells (>3000 rows), with either a value of 1 or 0 (call this column A). The value will depend on the value in column B...

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 =...

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...

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...

sum up each individual values from 2 arrays

javascript,arrays,sum,element
I'm trying to understand this conditional loop to sum up each elements from 2 arrays, but I stumble upon the latter part, I don't understand what is to be achieved there. Can you please explain to me? function Arrays_sum(array1, array2) { var result = []; var ctr = 0; var...

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...

R: sum positive values and sum negative values

r,vector,sum
I've got a vector: vec <- c(1,-2,9,-7,7,4,5,2,1,-10) Now I would like to take the sum of the negative values in vec, and the sum of the positive values in vec. neg <- sum of the negative values in vec pos <- sum of the positive values in vec ...

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....

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...

Python Pandas sum of dataframe with one column

python-2.7,pandas,sum,dataframes,calculated-columns
I have a Python Pandas DataFrame: df = pd.DataFrame(np.random.rand(5,3),columns=list('ABC')) print df A B C 0 0.041761178 0.60439116 0.349372206 1 0.820455992 0.245314299 0.635568504 2 0.517482167 0.7257227 0.982969949 3 0.208934899 0.594973111 0.671030326 4 0.651299752 0.617672419 0.948121305 Question: I would like to add the first column to the whole dataframe. I would like...

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...

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...

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...

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...

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....

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...

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...

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...

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 :...

make sum of an empty set/set of NA's NA instead of 0?

r,sum,na
The sum function returns 0 if it is applied to an empty set. Is there a simple way to make it return NA if it is applied to a set of NA values? Here is a borrowed example: test <- data.frame(name = rep(c("A", "B", "C"), each = 4), var1 =...

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...

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...

How to find top usage of IP pairs in PostgreSQL?

sql,postgresql,select,sum
I have a table with source_ip and destination_ip and usage. now i want to find top usage for ip pairs. My table is like this: source_ip | destination_ip | usage 192.168.1.1 | 192.168.1.2 | 20 192.168.1.2 | 192.168.1.1 | 30 192.168.1.3 | 192.168.1.2 | 20 192.168.1.2 | 192.168.1.3 | 20...

Sum on case expression when working with dates

sql,sql-server,date,sum,case
I'm looking to create a view which will output the data in the following format AgedPeriod BillValue Status <1 35000 Outstanding 1-3 23386 Outstanding 3-6 5000 Outstanding I can use the code below to SUM each case statement into a new column and I could name the column headings after...

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...

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...

Subtract two columns of different tables

sql,postgresql,sum,aggregate-functions,subtract
I have two unrelated tables: contribution(id,amount, create_at, user_id) solicitude(id, amount, create_at, status_id, type_id, user_id) I need to subtract the sum of the amount of the contribution and of the solicitude from a user, but that result can't to be negative. How can I do this? Function or query? I tried...

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...

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...

SUM case returns value without GROUP BY

mysql,sql,group-by,sum,case
When I add SUM around my case select, it returns the summed value without the GROUP BY. The query I am using, without the SUM, is the following SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id INNER...

How to perform boolean addition on an SQL select

sql,sql-server,select,sum,boolean
I have the following data in a database table column named timeSchedule 00100110 00010100 00110000 00110011 Boolean addition would result in 00110111 Is there a way to do this in sql? Something like select sumboolean(timeSchedule) from myTable Someone asked for DDL+DML.. here is an example: CREATE TABLE [dbo].[myTable]( [musPracticeID] [int]...

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...

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 * ....

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...

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...

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...

SUM of two timestampdiff in minutes

mysql,timestamp,sum
I've searched through many sites but was unable to find a solution to this. I'm trying to sum two timestampdiffs when they are in minutes: SELECT COUNT(*) from `table` WHERE TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE,first_date,second_date), TIMESTAMPDIFF(MINUTE,fourth_date,third_date) ) > 15 AND status='Pending' This is where I am currently at but it returns an empty...

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...

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 |...

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 |...