Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL absolute value sum and iterate

Lets say i have table with that looks something like this:

cns_amt ---- cusip_nbr

-3000 -------------------- 00162Q205
4000 -------------------- 00162Q205
6000 -------------------- 00162Q205
8000 -------------------- 00162Q205
10000-------------------- 33733B100
-2900 -------------------- 33733B100
1000-------------------- 33733B100
8000 -------------------- 33733B100
7000-------------------- 464286178
-1200 -------------------- 464286178
1000-------------------- 464286178
1000 -------------------- 464286178

How can I make it so I get the results:

total_amt ---- cusip_nbr

21000------------------------00162Q205
21900-----------------------33733B100
10200------------------------4642861

Basically I would like to sum each the absolute value for each distinct cusip_nbr and return a result that plots each cusip_nbr and its respective absolute value sum. (Only three distinct cusip_nbr 's are shown here but i have hundreds of them, each with a cns_amt that needs to be summed)

like image 389
euge1220 Avatar asked Jul 17 '13 19:07

euge1220


1 Answers

You can use ABS() to get the absolute value, and SUM():

SELECT cusip_nbr, SUM(ABS(cns_amt)) 'total_amt'
FROM Table
GROUP BY cusip_nbr

Demo: SQL Fiddle

like image 157
Hart CO Avatar answered Sep 20 '22 01:09

Hart CO