【问题标题】:Division of integers returns 0整数除法返回 0
【发布时间】:2014-10-23 20:45:45
【问题描述】:

我觉得我错过了一些明显的东西。我正在尝试测试random() 的分布。这是表格:

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 列更改为十进制而不是整数,结果始终相同。

Here is a fiddle.

任何关于我做错了什么的见解?

【问题讨论】:

  • 投到numeric(或float,虽然我更喜欢前者)你分裂之前。
  • 您可以在一行中重现此内容:select 1/2。返回 0。
  • @Phrancis,你应该在 之前进行转换:select 1/2, 1.0/2, 1.0*1/2, 1::numeric/2, cast(1 as float)/2;

标签: sql postgresql division


【解决方案1】:

您应该在除法之前进行转换,但您也缺少一个子查询来从表中获取总数。 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;

【讨论】:

  • 我知道这与选角有关,所以感谢 6 年后仍然是一个有用的答案!在我的情况下,我将整个 calc 转换为 decimal(10,2),它产生 0,但转换单个组件是一种享受。还在学习!
  • 只要转换其中一个数字(例如分子)即可,然后整个表达式变为十进制。
【解决方案2】:

试试这个查询:

select 
       random_int,
       count(random_int) as Count,
       cast( count(random_int) / max(id) as float) as Percent,
       (100.0 * count(random_int) / max(id))::numeric(5,2) as pct
  from test
 group by random_int
 order by random_int;

PostgreSQL 有一个强大的类型系统。在您的情况下,count() 函数隐含了类型,该函数返回bigint(或int8)和id 列,即integer

我建议使用100.0 作为初始乘数,这将导致整个表达式被计算为数字,并且还将提供实际百分比。您可能还想在最后转换为 numeric(5,2) 以消除太大的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多