Question

I have the following situation:

ACCT_TABLE

ID|TYPE|AMT
--+----+---
A |CR  |  5
A |DR  |  5
B |CR  |  2
B |CR  |  4
B |DR  |  2
B |DR  |  2
C |CR  |  1
C |CR  |  1

I am trying to build a query that produces the following results:

DESIRED RESULT

ID|BAL
--+---
A |  0
B |  2
C |  2


ACTUAL RESULT

ID|BAL
--+----
A | -10
B |  -8
C |   2

I'm not sure how to sum the values in amount based on the value in the TYPE column.

I have the following:

    select id, sum(
        case
        when
            type = 'CR'
            then AMT
            else -AMT
        end
    ) as BAL
    from acct_table
group by id;
Was it helpful?

Solution

I have tested your query in , , , and it produced desired results.

Your Query

SELECT id
       ,SUM(CASE WHEN type = 'CR' THEN AMT
                 ELSE -AMT
            END) AS BAL
    FROM acct_table
    GROUP BY id;

My Query

SELECT id
       ,SUM(CASE WHEN type = 'CR' THEN AMT
                 ELSE ( AMT * -1 )
            END) AS BAL
    FROM acct_table
    GROUP BY id;

test - http://sqlfiddle.com/#!4/0b8cb/1

test- http://sqlfiddle.com/#!2/0b8cbd

test - http://sqlfiddle.com/#!15/0b8cb/1

Please verify that data in your table matches what you have shown in the question.

OTHER TIPS

I tested a query performing summing like that in DB2 (9.7 LUW), and it also worked.

There appears to be nothing wrong with your query; it must be something else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top