SQL Server:具有字母数字值的列的总和

问题描述 投票:0回答:3

我想获取字母数字列的总和。我想添加数字值,如果不是数字,则返回列值。我所做的是添加一个看起来像这样的CASE WHEN

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

因此,我假设将添加所有数值,并且如果值位于('CL', 'HS', 'HV', 'ML', 'SL', 'VL', 'HC', 'S', '*')中,则将按原样返回。

但是我得到

将数据类型nvarchar转换为数字时出错。

sql sql-server case-when alphanumeric
3个回答
2
投票

似乎您的SUM聚合不正确。仅在case语句中的条件为true时才求和。试试这个:

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

[如果您不知道非数值的确切组合,可以使用ISNUMERIC函数(假设您使用的是SQL Server)来测试该值是否为数字,如果为0,则指定为0并非如此,汇总最终结果。

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

要汇总数值并且也保持非数值,可以这样使用联合查询:

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

0
投票

这看起来像SQL Server语法。我建议使用TRY_CONVERT()

TRY_CONVERT(DECIMAL, intAllocatedResourceperDivision) as intAllocatedResourceperDivision

0
投票

尝试一下:

select 'CL' as intAllocatedResourceperDivision into #tmp
union select 'HS'union select 'HV'union select 'ML'union select 'SL'union select 'VL'union select 'HC'union select 'S'union select '*'union select '1'union select '4'

select CAST(SUM(ISNULL(CAST(intAllocatedResourceperDivision AS DECIMAL),0.00)) AS nvarchar(250)) as intAllocatedResourceperDivision
from #tmp where intAllocatedResourceperDivision NOT IN ('CL','HS','HV','ML','SL','VL','HC','S','*')
union 
select intAllocatedResourceperDivision
from #tmp where intAllocatedResourceperDivision IN ('CL','HS','HV','ML','SL','VL','HC','S','*')
© www.soinside.com 2019 - 2024. All rights reserved.