

用Cast,只要将参与运算的任一数转为浮点数,运算结果就会有小数
方法1:不能保留负数
select bb.shopname,bb.lw,bb.tw,round(cast(bb.tw as float)/bb.lw,4)*100 bf from (select a.shopname,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=1) as lw,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=0) as tw from shopname as a) as bb
方法2:可以保留负数
select bb.shopname,bb.lw,bb.tw,round((cast(bb.tw as float)-bb.lw)/bb.lw*100,2) bf from (select a.shopname,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=1) as lw,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=0) as tw from shopname as a) as bb
两个数中任意一个转换为浮点数后,整型的就会转换为浮点数再进行运算
select cast ( 165*100 as float )/343
select str((4*100.0)/(20*1.0),5,2)
select str((165*100.0)/(343*1.0),5,2)
如果要保留固定小数位,使用 cast(xxxxxx as numeric(10,2)) 的形式整理结果。
select bb.shopname,bb.lw,bb.tw,cast(bb.tw as float)/bb.lw from (select a.shopname,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=1) as lw,(select sum(salesmoney) from salesdata where shopname=a.shopname and datediff(week,[salesday],getdate())=0) as tw from shopname as a) as bb
CONCAT(CAST(ROUND((2/10)*100,2) AS CHAR),'%')