我正在制作一个除法公式,为新列提供6位小数。
dt LD_VOY_N LD_VSL_M
2017-04-29 12:00:00.000 0014S rmhp tpcp
2017-04-29 16:00:00.000 0014S rmhp tpcp
2017-04-29 20:00:00.000 0014S rmhp tpcp
2017-04-30 08:00:00.000 0014S rmhp tpcp
2017-04-30 12:00:00.000 0014S rmhp tpcp
2017-01-05 04:00:00.000 0014S rmhp tpcp
2017-01-05 08:00:00.000 0014S rmhp tpcp
2017-01-05 12:00:00.000 0014S rmhp tpcp
2017-02-05 04:00:00.000 0014S rmhp tpcp
2017-02-05 08:00:00.000 0014S rmhp tpcp
x y
12 126
16 110
5 105
3 102
1 101
13 88
26 62
5 57
39 18
18 0
我试图将x列除以y列,但是,当我这样做时,输出不正确。以下是我正在处理的代码。
SELECT dt, LD_VOY_N, LD_VSL_M , x,y, ISNULL(x/ NULLIF((y),0),0) as conditional_probability
以下是我的输出示例。
dt LD_VOY_N LD_VSL_M
2017-04-29 12:00:00.000 0014S rmhp tpcp
2017-04-29 16:00:00.000 0014S rmhp tpcp
2017-04-29 20:00:00.000 0014S rmhp tpcp
2017-04-30 08:00:00.000 0014S rmhp tpcp
2017-04-30 12:00:00.000 0014S rmhp tpcp
2017-01-05 04:00:00.000 0014S rmhp tpcp
2017-01-05 08:00:00.000 0014S rmhp tpcp
2017-01-05 12:00:00.000 0014S rmhp tpcp
2017-02-05 04:00:00.000 0014S rmhp tpcp
2017-02-05 08:00:00.000 0014S rmhp tpcp
x y divided
12 126 0
16 110 0
5 105 0
3 102 0
1 101 0
13 88 0
26 62 0
5 57 0
39 18 0
18 0 2
以下是我想要的输出。
dt LD_VOY_N LD_VSL_M
2017-04-29 12:00:00.000 0014S rmhp tpcp
2017-04-29 16:00:00.000 0014S rmhp tpcp
2017-04-29 20:00:00.000 0014S rmhp tpcp
2017-04-30 08:00:00.000 0014S rmhp tpcp
2017-04-30 12:00:00.000 0014S rmhp tpcp
2017-01-05 04:00:00.000 0014S rmhp tpcp
2017-01-05 08:00:00.000 0014S rmhp tpcp
2017-01-05 12:00:00.000 0014S rmhp tpcp
2017-02-05 04:00:00.000 0014S rmhp tpcp
2017-02-05 08:00:00.000 0014S rmhp tpcp
x y divided
12 126 0.095238
16 110 0.145454
5 105 0.047619
3 102 0.029411
1 101 0.009900
13 88 0.147727
26 62 0.419354
5 57 0.087719
39 18 0.461538
18 0 0
你们有没有关于如何获得所需输出的想法?请帮忙,因为我已经被困在这里很长一段时间了。
答案 0 :(得分:0)
试试这个
create table #testa ( x int , y int )
insert into #testa (x,y) values (12,126)
select x,y , cast(cast (x as float)/cast (case when isnull(y,0) =0 then 1 else y end as float) as decimal(19,6)) from #testa
谢谢
答案 1 :(得分:0)
你可以试试这个:
declare @tbl table(
x int,
y int
)
insert into @tbl(x,y)
values
(12,126),
(16,110),
(18,0)
;
SELECT x,y,
case when y = 0 then 0
else
round((cast(x as decimal(12,6)) / cast(y as decimal(12,6))), 6)
end as divided
from @tbl
在分割之前,将int值转换为decimals
,然后Round
将最终结果值转换为6
小数位。