0

I have a varchar field AMOUNT in DB2.

Possible table state values:

ID            AMOUNT
-------------------------
1             123.4578
2              NULL
2             123.78
1            -8562.85441
2            
1             0.0
-------------------------

Column AMOUNT can be empty as the second last row above depicts.

I want to do a SUM over the AMOUNT group by ID in a query.

The result SUM should be DECIMAL(16,2).

What will be the correct way to do that considering that the value can be both null and empty and also the number of digits after the decimal is not following any fixed format?

It's a duplicate of this question, but the answers given are not complete and not accepted.

Thanks for reading!

1
  • basically if(amount is null OR amount = '') then 0 else amount, in pseudo-code. this column should be done numerically, though. a numeric column wouldn't allow an "empty" value, which is a string. a number is either null, or an number.
    – Marc B
    Aug 11, 2014 at 15:53

2 Answers 2

1

I think the code you want is:

select (case when amount <> '' then cast(amount as float) end)
from table t;

You don't have to worry about NULL values. sum() ignores them. If you want to get 0 if all values are NULL/blank, then add else 0 to the case statement.

If you are concerned about other non-numeric values, you can try:

select (case when amount <> '' and
                  not regexp_like(amount, '[^0-9.]', '')
             then cast(amount as float) end
from table t;
4
  • Getting below error: Error: DB2 SQL Error: SQLCODE=-461, SQLSTATE=42846, SQLERRMC=SYSIBM.CHARACTER;SYSIBM.DOUBLE, DRIVER=3.50.152
    – Vicky
    Aug 11, 2014 at 16:16
  • @Vicky . . . You should edit your question and show the code that you are running. Aug 11, 2014 at 22:06
  • The translate statements is not correct. All DB2 translate specifications I am able to find are TRANSLATE( string_expression [, to_string [, from_string [, pad ]]] ). I am not sure how it works on other systems but IBMi will not take and empty string for to or from string.
    – Peter
    Feb 16, 2021 at 0:05
  • @Peter . . . That is a really good point. I replaced it regexp_like(). Feb 16, 2021 at 1:12
0
CAST(CASE WHEN ISNULL(AMOUNT, '') = '' THEN NULL ELSE REPLACE(AMOUNT, ',', '.') END AS DECIMAL (16,2))  AS AMOUNT

or

CAST (123.4578 AS DECIMAL (16,2))
+ CAST (NULL AS DECIMAL (16,2))
+ CAST (123.78 AS DECIMAL (16,2))
+ CAST (-8562.85441 AS DECIMAL (16,2))

= RESULT DECIMAL(16,2)
1
  • It would be more helpful if you could add some comments or description on how or why your answer works.
    – Anurag A S
    Jun 19, 2020 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.