简体   繁体   English

将 nvarchar 值转换为 Decimal 或 Numeric 数据类型?

[英]Convert nvarchar value to Decimal or Numeric datatype?

I have a column called 'Market value' in my SQL table where values of this column is like '+000000034567.4563' (18 char length including + symbol) and datatype is NVARCHAR .我的 SQL 表中有一个名为 'Market value' 的列,其中该列的值类似于 '+000000034567.4563'(18 个字符长度,包括 + 符号),数据类型为NVARCHAR

I need to apply group by and take sum of 'Market Value' but group by does not work with NVARCHAR data type.我需要应用 group by 并计算“市场价值”的总和,但 group by 不适用于NVARCHAR数据类型。 So I am converting using CONVERT .所以我正在使用CONVERT进行CONVERT

SELECT CONVERT(Numeric(18,4), '+000000034567.4563') 

But I am getting output is '34567.4563' But my expectation is '+000000034567.4563'.但我得到的输出是“34567.4563”但我的期望是“+000000034567.4563”。

How can I achieve this using SQL?如何使用 SQL 实现这一点?

you could use Format to convert it to your desired string representation again like this您可以使用 Format 再次将其转换为您想要的字符串表示形式

SELECT format(CONVERT(numeric(18,4), '+000000034567.4563'), '+000000000000.0000') 

and use it to calculate and then format并用它来计算然后格式化

SELECT format(sum(CONVERT(numeric(18,4), yt.[Market Value])), '+000000000000.0000')
from yourtable yt
group by yt.whatever

Check this code if it will help you in any way.检查此代码是否会以任何方式帮助您。 It was written on MySQL Language.它是用 MySQL 语言编写的。

Select Concat(Left(Market_Value,1),
        Repeat('0',(Length(Market_value)-Length(concat(left(Market_Value,1),
        sum(substring(Market_value,2,Length(Market_Value))))))),
        sum(substring(Market_value,2,Length(Market_Value)))) as Market_Value 
        from Test57 group by Market_value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM