Division of integers returns 0

后端 未结 2 371
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 2020-11-30 13:06

    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 讨论(0)
提交回复
热议问题