代码之家  ›  专栏  ›  技术社区  ›  Andres Urrego Angel

红移除法的结果不包括小数

  •  6
  • Andres Urrego Angel  · 技术社区  · 6 年前

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

    代码:

    select 1701 / 84936;
    

    输出:

    enter image description here

    我尝试过:

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

    但结果是 0.0000000000 .

    我怎么能解决这个愚蠢的问题?

    2 回复  |  直到 6 年前
        1
  •  9
  •   Lukasz Szozda    6 年前

    它是整数除法。确保至少有一个参数是: NUMERIC (精确数据类型)/ FLOAT (注意:这是近似数据类型):

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

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

    DBFiddle Demo

        2
  •  0
  •   ePi272314    5 年前

    混合类型时,顺序计数

    另外,请注意,数学表达式中的数字顺序很重要。
    假设我们打算计算百分比 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将强制进行非整数计算。