整数除法返回0 [英] Division of integers returns 0
本文介绍了整数除法返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我觉得我缺少明显的东西。我正在尝试测试 random()
的分布。表格如下:
I feel like I'm missing something obvious. I am trying to test out the distribution of random()
. Here is the table:
create table test (
id int,
random_float float,
random_int int
);
这就是我想做的:
truncate table test;
insert into test (id)
values (generate_series(1,1000));
update test
set
random_float = random() * 10 + 1;
update test
set
random_int = trunc(random_float);
select
random_int,
count(random_int) as Count,
cast( count(random_int) / max(id) as float) as Percent
from test
group by random_int
order by random_int;
但是,百分比列为每条记录返回零。我尝试将其强制转换为浮点数,将其转换为十进制,然后尝试将 random_int
列更改为十进制,而不是整数,始终保持相同的结果。
However, the "Percent" column returns zero for every record. I tried casting it as float, as decimal, I tried changing the random_int
column to decimal instead of integer, always same result.
对我在做什么错有任何见解吗?
Any insight as to what I am doing wrong?
推荐答案
您应该在进行除法运算之前进行强制转换,但同时也缺少子查询以从表中获取总计数。 这里是示例。
You should cast before you divide, but also you were missing a subquery to get the total count from the table. Here's the sample.
select
random_int,
count(random_int) as Count,
cast(count(random_int) as decimal(7,2)) / cast((select count(random_int) from test) as decimal(7,2)) as Percent
from test
group by random_int
order by random_int;
这篇关于整数除法返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文