2

我有以下查询,但距离结果超过一位,我希望它仅为 2 位。

UPDATE Customer 
SET Distance = CAST(CAST(REPLACE(REPLACE(distance, 'km' , '' ), 'miles', '')as float) * 1.3 * 0.62137 AS NVARCHAR) + 'Miles' 
FROM customer

如果我有这样的结果,2.3434453433那么我希望它更改为2.3

4

4 回答 4

1
SELECT 
CAST(CAST(CAST(REPLACE(REPLACE(distance, 'km' , '' ), 'miles', '')as float) * 1.3 * 0.62137 AS DECIMAL(19,1)) AS NVARCHAR) 
+ 'Miles' FROM customer
于 2013-07-10T10:27:41.220 回答
1

我不清楚为什么要将值存储为字符串,而不是仅在输出时对其进行格式化。

你的表达好像有点糊涂,乘以1.3再乘以0.62。我想你想要这样的东西:

UPDATE Customer
    set Distance = (case when right(distance, 3) = ' km'
                         then replace(str(cast(left(distance, charindex(' ', distance) - 1),
                                       as float)/0.62137, 6, 1), ' ', '') + 'Miles'
                         else distance
                    end)

str()函数将数字转换为具有给定长度和精度的指定字符串格式。

但是,您似乎真的应该将Customer表格更改为具有距离、单位和“DistanceMiles”字段,该字段是结合其他两个值的计算列。它会是这样的:

    DistanceMiles as (case when Units = 'Mile' 
                           then replace(str(Distance, 6, 1), ' ', '')+' Miles'
                           when Units = 'km'
                           then replace(str(Distance/0.62137, 6, 1), ' ', '')+' Miles'
                      end)
于 2013-07-10T10:37:13.370 回答
1

方法 :

这是方法的 SQLFiddel 演示

select Convert(varchar(3),convert(numeric(5,1),(2.3434453433)))

解决方案 :

UPDATE Customer 
   set Distance= Convert(varchar(3),Convert(Numeric(5,1),
                    CAST(CAST(REPLACE(REPLACE(distance, 'km' , '' ),
                   'miles', '')as float) * 1.3 * 0.62137 AS NVARCHAR))) + 'Miles' 
于 2013-07-10T10:24:14.977 回答
1

如果您使用舍入值,则可以使用舍入函数

UPDATE Customer set Distance=
    CAST(round(CAST(REPLACE(REPLACE(distance, 'km' , '' ), 'miles', '')as float) * 1.3 * 0.62137,1) AS NVARCHAR) 
    + 'Miles' FROM customer
于 2013-07-10T10:25:50.480 回答