Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 SQL Help...SUM

Author  Topic 

jrockfl
Posting Yak Master

223 Posts

Posted - 2004-11-19 : 16:46:40
How can I return 12 and and 67.8? The third item is a credit..

rep sales amt
SP107 67.8 12
SP107 4.99 1
SP107 -4.99 1

lazerath
Constraint Violating Yak Guru

343 Posts

Posted - 2004-11-19 : 16:49:44
[code]
SELECT --rep,
SUM(sales) as SalesTotal
SUM(CASE WHEN sales < 0 THEN amt * -1 ELSE amt END) as AmtTotal
FROM MyTable
--GROUP BY rep;
[/code]
Go to Top of Page

jrockfl
Posting Yak Master

223 Posts

Posted - 2004-11-19 : 16:55:46
perfect! that worked, i learned something new....seems like you do just about anything with SQL.
Thank you!!
Go to Top of Page

jrockfl
Posting Yak Master

223 Posts

Posted - 2004-11-19 : 16:59:59
how can i add one more case? case when sales = 0 then amt = 0
Go to Top of Page

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2004-11-19 : 17:03:04
SUM(CASE WHEN sales < 0 THEN amt * -1 WHEN sales=0 THEN 0 ELSE amt END) as AmtTotal


Go with the flow & have fun! Else fight the flow
Go to Top of Page

jrockfl
Posting Yak Master

223 Posts

Posted - 2004-11-19 : 21:20:59
Thank you!
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2004-11-19 : 21:36:16
Here's a slightly shorter version that should also work:

SELECT Sum(Sign(sales) * amt) AS AmtTotal

The Sign() function returns a -1, 0, or 1 for negative, zero, or positive values, respectively. Multiplying by this value would give the same effect as the full CASE expression does.
Go to Top of Page

jrockfl
Posting Yak Master

223 Posts

Posted - 2004-11-19 : 22:12:51
I will try that solution too. Thank you. I didnt know SQL can do trig too!
Go to Top of Page
   

- Advertisement -