Search code examples
sqlsql-servercase-whenalphanumeric

SQL Server : SUM of column with alphanumeric values


I want to get the sum of a column that is alphanumeric. I want to add numeric values and return column values if not numeric. What I did is a added a CASE WHEN that looks like this

CASE 
   WHEN intAllocatedResourceperDivision NOT IN ('CL', 'HS', 'HV', 'ML', 'SL', 'VL', 'HC', 'S', '*') 
      THEN CAST(SUM(ISNULL(CAST(intAllocatedResourceperDivision AS DECIMAL), 0.00)) AS NVARCHAR(250)) 
      ELSE intAllocatedResourceperDivision 
END intAllocatedResourceperDivision

So I assume that all numeric values will be added and if values is in ('CL', 'HS', 'HV', 'ML', 'SL', 'VL', 'HC', 'S', '*') it will be returned as is.

But I'm getting

Error converting data type nvarchar to numeric.


Solution

  • Looks like your SUM aggregation is out of place. You only sum if the condition in the case statement is true. Try this:

    SUM(case when intAllocatedResourceperDivision NOT IN ('CL','HS','HV','ML','SL','VL','HC','S','*') THEN intAllocatedResourceperDivision else 0 end)
    

    In case you don't know the exact potential combination of non numeric values, you can use the ISNUMERIC function (assuming you're using SQL Server) to test whether or not the value is a number and assign a 0 if it's not, aggregating the final result.

    SUM(case when ISNUMERIC(intAllocatedResourceperDivision) = 1 then intAllocatedResourceperDivision else 0 end)
    

    To aggregate the numerical values and also keep non-numerical, you can use a union query as such:

    select
        cast(SUM(cast(intAllocatedResourceperDivision as decimal(18,2))) as varchar)
    from
        YOUR_TABLE
    where
        ISNUMERIC(intAllocatedResourceperDivision) = 1
    
    UNION ALL
    
    select
        intAllocatedResourceperDivision
    from
        YOUR_TABLE
    where
        ISNUMERIC(intAllocatedResourceperDivision) = 0