SQL 服务器:具有字母数字值的列的总和

SQL Server : SUM of column with alphanumeric values

我想获取字母数字列的总和。如果不是数字,我想添加数值和 return 列值。我所做的是添加一个 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', '*') 中,它将按原样 return 编辑。

但我得到

Error converting data type nvarchar to numeric.

这看起来像 SQL 服务器语法。我建议使用 TRY_CONVERT():

TRY_CONVERT(DECIMAL, intAllocatedResourceperDivision) as intAllocatedResourceperDivision

看起来您的 SUM 聚合不合适。只有在 case 语句中的条件为真时才求和。试试这个:

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

如果您不知道非数值的确切潜在组合,您可以使用 ISNUMERIC 函数(假设您使用的是 SQL 服务器)来测试是否value 是一个数字,如果不是,则分配一个 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

试试这个:

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','*')