2017-03-15 20 views
0

我很担心我的结果将数字转换为非小数点和逗号分隔。我需要实现正确的格式并将数字四舍五入为货币,如下面的示例中所示。请帮帮我。如何在T-SQL中格式化和舍入数字?

select sum([TRANSACTION_PRICE]) from [dw_property_detail] 

错误结果:520400958.9
正确的结果:520,400,959

select sum(nullif([ACTUAL_SIZE],0)) from [dw_property_detail] 

错误结果:25595.5
正确的结果:(25,596)

select (Min(TRANSACTION_PRICE/ACTUAL_SIZE)) from [dw_property_detail] 

错误结果:3241412.6
正确的结果:($3,241,413)

+1

在一般情况下,如果你对SQL Server上的应用程序,你应该做的格式那里。 – Aron

回答

0

鉴于它是2017年,我会说有两个正确的答案。

  1. 根据需要使用2012年推出的FORMAT函数,并使用适当的代码输出所需的结果。
  2. 格式化应尽可能在客户端完成。
-1

正如上面提到的格式化应该留给客户端,但您可以将您的金额转换为十进制数,然后将其转换为金钱并使用格式为1来添加逗号。你可以摆脱.00与子,如果你想

select convert(varchar(50), convert(money, convert(decimal, YourValue)), 1) 

money format

1逗号每三位数字的小数点左边,两位小数点的权利;例如,3,510.92。

或者:

select '$ ' + reverse(stuff(reverse(convert(varchar(50), convert(money, convert(decimal, YourValue)), 1)), 1, 3, '')) 
0

我敢肯定很多人会同意,格式在表示层所属。

也就是说,下面应该有所帮助。我还应该补充一点,Format()有一些很棒的功能,它并不是一个表演者。

Declare @YourTable table (SomeVal decimal(18,2)) 
Insert Into @YourTable values 
(-3241412.6), 
(520400958.9) 

Select Format(abs(round(SomeVal,0)),IIF(SomeVal<0,'($#,###)','$#,###')) 
From @YourTable 

返回

($3,241,413) 
$520,400,959 
-1

它这样很难记住这么多东西,

Declare @YourTable table (SomeVal decimal(18,2)) 
Insert Into @YourTable values 
(3241412.6), 
(520400958.9),(25595.5) 

select FORMAT(round(SomeVal,0), 'C', 'en-us') 
from @YourTable 
+0

我可以知道为什么它被降低了吗?它给出了正确的结果。 – KumarHarsh