Separate SUM results on a single line

15 pts.
Tags:
DB2
DB2 Views
SUM function
SUM statement
Can DB2 return separate SUMfunction within one statement. If I have : SELECT BRANCH,SUM(AMOUNT) ,COUNT(*) FROM TableA WHERE BRANCH IN (180002,180092) gives

Branch,Amount,Count

180002,+100,3

can I return two SUMs - one for positive values of amount and one for negative amounts so will get :

 Branch, credit, debits, Count

 180002, -100,+200,3



Software/Hardware used:
IBM DB2 v9

Answer Wiki

Thanks. We'll let you know when a new response is added.

As mentioned in the discussion below, the subquery needs to be named.

Discuss This Question: 2  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • carlosdl
    You could use the SIGN and DECODE functions, if they are available on your version/platform. Something like this:
    SELECT 
    	branch, 
    	SUM(DECODE(SIGN(amount),-1,amount,0)) SUM_NEG,
    	SUM(DECODE(SIGN(amount),-1,0,amount)) SUM_POS, 
    	COUNT(*)
    FROM TableA
    ...
    If these functions are not available, you could use a CASE expression.
    68,780 pointsBadges:
    report
  • PeterWarren
    Guys, not sure how to 'approve' the answer but I haven't access to the DECODE but Phil's CASE suggestion worked 9with one minor correction - I needed to name the subquery). Many thanks for your help, Pete.
    15 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following