Sql根据条件截断到小数位

时间:2014-03-19 07:09:53

标签: sql-server-2008 truncate

我有一个要求

DECLARE @Test TABLE   
(Id int not null,
 AMOUNT decimal(20,3) not null)
 Insert into @Test values(1, 100.943)
 Insert into @Test values(2, 100.000)
 Insert into @Test values( 3,100.943)


SELECT Id,
case 
when Id = 2 then 
 CAST(ROUND(AMOUNT,2,4) AS DECIMAL(19,2))  
 else AMOUNT
 end as AMOUNT
 from @Test

但它不会产生预期的结果。 返回的结果是

Id  AMOUNT
1   100.943
2   100.000
3   100.943

如果Id = 2

,我怎样才能将金额截断为2位小数

预期结果是

Id  AMOUNT
1   100.943
2   100.00
3   100.943

1 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT Id,
case 
when Id = 2 then 
 ROUND(AMOUNT,2,2) 
 else AMOUNT
 end as AMOUNT
 from @Test

该回合的输入为ROUND ( numeric_expression , length [ ,function ] )。这意味着您将其四舍五入为4 decimal