Division of integers returns 0

后端 未结 2 372
天命终不由人
天命终不由人 2020-11-30 12:23

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 in         


        
2条回答
  •  一向
    一向 (楼主)
    2020-11-30 12:56

    Try this query instead:

    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 has a strong types system. In your case, type is implied by count() function, which returns bigint (or int8) and id column, which is integer.

    I would recommend using 100.0 as initial multiplier, that'll cause whole expression to be calculated as numeric and will also provide real percents. You might also want to cast to numeric(5,2) at the end to get rid of too big number.

提交回复
热议问题