Question

The table MTEL has 7 million rows. [TRANSACTION_AMT] column is varchar and some values are numeric whereas some values are blank spaces and some are 'NA'. Since I am returning absolute sum on column [TRANSACTION_AMT], I have used following query -

select  
    e.[ ACCOUNT_NUM] as acct_num
    ,'MTL' as src
    ,case 
        when isnumeric([TRANSACTION_AMT]) = 1 then SUM(ABS([TRANSACTION_AMT]))
        when [TRANSACTION_AMT] = 'NA' then SUM(ABS(REPLACE([TRANSACTION_AMT],'NA','0')))
        when [TRANSACTION_AMT] = '' then SUM(ABS(REPLACE([TRANSACTION_AMT], '', '0')))
   end as abs_total_txn_amt
from 
   mtb..MTEL e (nolock)
group by  
   e.[ACCOUNT_NUM], e.[TRANSACTION_AMT]

The above query throws an error

Error converting data type varchar to float.

after returning 4.4 million records.

What can I change in my code to get rid of error? I am using SQL Server.

Was it helpful?

Solution

You are doing the numeric logic after the sum(). You need to do it inside the sum():

select  e.[ ACCOUNT_NUM] as acct_num, 'MTL' as src
        sum(case when isnumeric([ TRANSACTION_AMT]) = 1 then ABS([ TRANSACTION_AMT])
                 else 0
            end) as abs_total_txn_amt
from mtb..MTEL e (nolock)
group by  e.[ ACCOUNT_NUM];

And, you probably don't want e.[ TRANSACTION_AMT] in the group by.

I also simplified the logic so you are only adding up valid numeric values. It treats everything else as 0.

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