Redshift除法结果不包括小数

时间:2018-05-23 17:47:04

标签: sql amazon-redshift

我正在尝试做一些非常基本的事情来计算Redshift中两列之间的一种百分比。但是,当我使用示例运行查询时,结果只是零,因为小数没有被覆盖。

代码:

select 1701 / 84936;

输出:

enter image description here

我试过了:

select cast(1701 / 84936 as numeric (10,10));

但结果是0.0000000000

我怎么能解决这个愚蠢的事情?

2 个答案:

答案 0 :(得分:6)

是整数除法。确保至少有一个参数是:NUMERIC(准确数据类型)/ FLOAT(警告:它是近似数据类型):

  

/ division(整数除法截断结果)

select 1701.0 / 84936;
-- or
SELECT 1.0 * 1701 / 84936;
-- or
SELECT CAST(1701 AS NUMERIC(10,4))/84936;

<强> DBFiddle Demo

答案 1 :(得分:0)

混合类型时,订单计数

此外,请注意,数学表达式中的数字顺序很重要。
假设我们打算计算两个列(或数字)均为整数的百分比unit_sales/total_sales

代码(http://tpcg.io/RMzCvL

-- Some dummy table
drop table if exists sales;
create table sales as 
    select 3 as unit_sales, 9 as total_sales;

-- The calculations
select
    unit_sales/total_sales*100,
    unit_sales/total_sales*100.0,
    100.0*unit_sales/total_sales
from sales;

输出

  0 | 0.0 | 33.33
  1. 第一列为0(整数),因为整数除法中3/9 = 0。
  2. 第二列是0.0,因为我们首先获得了整数0,然后将其转换为非整数。
  3. 预期结果。非整数100.0将强制执行非整数计算。