如何对字母数字列求和
How to sum the alpha numeric column
我有一列(附在下面),其中包含字母数字值,我需要对其所有值求和。
Percentage
----------
50.6687 percent
36.0178 percent
33.1196 percent
29.7688 percent
7.6338 percent
97.1024 percent
40.7949 percent
161.56 percent
我试过这段代码,但最后出错了
SUM(CAST(S.FIELD_PERCENTAGE AS FLOAT)) OVER() [Sum of PERCENTAGE]
错误是
Msg 8114, Level 16, State 5, Line 8
Error converting data type nvarchar to float.
我怎样才能达到这个预期的结果:
Percentage Sum of Percentage
---------- ----------------
50.6687 percent 456.666
36.0178 percent 456.666
33.1196 percent 456.666
29.7688 percent 456.666
7.6338 percent 456.666
97.1024 percent 456.666
40.7949 percent 456.666
161.56 percent 456.666
50.6687 percent
不是有效数字,因此为了用它计算,请在您的 CAST
中尝试 TRIM(REPLACE(S.FIELD_PERCENTAGE, 'percent', ''))
DECLARE @t TABLE(
FIELD_PERCENTAGE varchar(50)
)
INSERT INTO @t VALUES
('50.6687 percent')
,('36.0178 percent')
,('33.1196 percent')
,('29.7688 percent')
,('7.6338 percent')
,('97.1024 percent')
,('40.7949 percent')
,('161.56 percent')
SELECT sum(cast(TRIM(REPLACE(S.FIELD_PERCENTAGE, 'percent', '')) AS FLOAT)) over() [Sum of PERCENTAGE]
FROM @t s
我使用了以下组合并取得了结果。
SUM(CAST(REPLACE(S.FIELD_PERCENTAGE,'Percent','')AS FLOAT)) OVER() AS [Sum of Percentage],
我有一列(附在下面),其中包含字母数字值,我需要对其所有值求和。
Percentage
----------
50.6687 percent
36.0178 percent
33.1196 percent
29.7688 percent
7.6338 percent
97.1024 percent
40.7949 percent
161.56 percent
我试过这段代码,但最后出错了
SUM(CAST(S.FIELD_PERCENTAGE AS FLOAT)) OVER() [Sum of PERCENTAGE]
错误是
Msg 8114, Level 16, State 5, Line 8
Error converting data type nvarchar to float.
我怎样才能达到这个预期的结果:
Percentage Sum of Percentage
---------- ----------------
50.6687 percent 456.666
36.0178 percent 456.666
33.1196 percent 456.666
29.7688 percent 456.666
7.6338 percent 456.666
97.1024 percent 456.666
40.7949 percent 456.666
161.56 percent 456.666
50.6687 percent
不是有效数字,因此为了用它计算,请在您的 CAST
TRIM(REPLACE(S.FIELD_PERCENTAGE, 'percent', ''))
DECLARE @t TABLE(
FIELD_PERCENTAGE varchar(50)
)
INSERT INTO @t VALUES
('50.6687 percent')
,('36.0178 percent')
,('33.1196 percent')
,('29.7688 percent')
,('7.6338 percent')
,('97.1024 percent')
,('40.7949 percent')
,('161.56 percent')
SELECT sum(cast(TRIM(REPLACE(S.FIELD_PERCENTAGE, 'percent', '')) AS FLOAT)) over() [Sum of PERCENTAGE]
FROM @t s
我使用了以下组合并取得了结果。
SUM(CAST(REPLACE(S.FIELD_PERCENTAGE,'Percent','')AS FLOAT)) OVER() AS [Sum of Percentage],