簡體   English   中英

SQL Server:包含字母數字值的列的總和

[英]SQL Server : SUM of column with alphanumeric values

我想得到一列字母數字的總和。 如果不是數字,我想添加數值並返回列值。 我所做的是添加一個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 轉換為數字時出錯。

看起來您的 SUM 聚合不合適。 您只在 case 語句中的條件為真時求和。 嘗試這個:

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

如果您不知道非數值的確切潛在組合,您可以使用ISNUMERIC函數(假設您使用的是 SQL Server)來測試該值是否為數字,如果不是則分配 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

這看起來像 SQL Server 語法。 我建議使用TRY_CONVERT()

TRY_CONVERT(DECIMAL, intAllocatedResourceperDivision) as intAllocatedResourceperDivision

嘗試這個:

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

cast您轉換為varchar以匹配您的IN運算符值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM