如何对两个nvarchar值进行除法

时间:2018-10-16 14:14:09

标签: sql sql-server

我想从数据中删除GB并计算已用百分比。

IF OBJECT_ID('tempdb..#temp8') IS NOT NULL DROP TABLE #temp8
    select (REPLACE(sdCardUsed,'GB',''))used ,
    (REPLACE(sdCardFree,'GB','') ) free,

    (REPLACE(sdCardTotal,'GB','')) Total  
            into #temp8
            from DeviceInfo  order by _id desc

  Select ((REPLACE(sdCardUsed,'GB','')used) 
    *100/(REPLACE(sdCardTotal,'GB','')total) From #temp8)
        as Percentage
        From #temp8
        from DeviceInfo  
        Where total Is Not Null OR Total !=''
        order by _id desc   

预期结果:

----------------------------------------------------------------------------
|  SdcardUsed        |  SdcardTotal | SdcardFree |  Expectec_Result        |
----------------------------------------------------------------------------
|   23.87GB          |    50.00GB   | 26.23GB    |    47.74%               |
----------------------------------------------------------------------------
|   0.76GB           |    20.79GB   | 20.03GB    |    3.655%               |
----------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:1)

如果将您的预期结果的前三列作为DeviceInfo的当前内容,则可以实现您的预​​期结果(给予或对类型进行一些改动),如下所示:

declare @DeviceInfo table (SdcardUsed varchar(15), SdcardTotal varchar(15), SdcardFree varchar(15))
insert into @DeviceInfo(SdcardUsed,SdcardTotal,SdcardFree) values
('23.87GB','50.00GB','26.23GB'),
('0.76GB' ,'20.79GB','20.03GB')

select
    di.*,(used * 100 / total) as UsedPercent
from
    @DeviceInfo di
        cross apply
    (values (CONVERT(decimal(15,5),REPLACE(SdCardUsed,'GB','')),
            CONVERT(decimal(15,5),REPLACE(SdCardTotal,'GB','')),
            CONVERT(decimal(15,5),REPLACE(SdCardFree,'GB','')))) t(used,total,free)

请注意,我没有使用free,而是将所有3个值从字符串转换为小数,只是为了展示常规技术。如果要查看di.*产生的所有列,可以仅用*替换apply

结果:

SdcardUsed      SdcardTotal     SdcardFree      UsedPercent
--------------- --------------- --------------- ----------------------
23.87GB         50.00GB         26.23GB         47.7400000000000000000
0.76GB          20.79GB         20.03GB         3.6556036556036556036