如何在 Oracle SQL 中除整数以产生浮点数?

How to divide integers in Oracle SQL to produce floating point numbers?

我刚开始学习 Oracle SQL。我想划分两列与整数相同的 numeric 数据类型。我想在 table 或 float 数据类型中创建一个新列,将现有 numeric 列除以一个整数并将其值放入 float 列。我将此代码用于划分和更新部分:

update Student set AVERAGE = TOTAL/3;

这里,TOTALnumeric 列,AVERAGEfloat。但是当我打印 table 使用:

select * from Student;

AVERAGE 显示为四舍五入的除法值。我尝试了两种在互联网上找到的解决方案:

update Student set AVERAGE = (TOTAL*1.00)/3;

并且:

update Student set AVERAGE = cast(TOTAL as float(2))/3;

但是两者都不起作用。我究竟做错了什么? 这是我得到的输出:

 ROLL_NO SNAME                MATHS       CHEM        PHY      TOTAL    AVERAGE
---------- --------------- ---------- ---------- ---------- ---------- ----------
       101 abcd                    56         68         80        204         70
       102 efgh                    81         78         70        229         80
       103 ijkl                    69         73         78        220         70
       104 mnop                    90         89         92        271         90
       105 qrst                    80         89         79        248         80

评论有点长

average 列将根据该列的数据类型显示。 oracle会把被除的"numbers"转换所以结果是准确的,我想用number类型。

你可以运行下面的代码看到除法结果总是一样的:

select cast(10 as int) / cast(3 as int),
       cast(10 as numeric) / cast(3 as numeric),
       cast(10 as float) / cast(3 as float)
from dual;

所以操作数的数据类型没有区别。

另一方面,结果的数据类型是。这些会产生不同的结果:

select cast(10 / 3 as int),
       cast(10 / 3 as float),
       cast(10 / 3 as number),
       cast(10 / 3 as numeric(5, 1))
from dual;

首先,你需要了解Oracle中的FLOAT数据类型是什么意思。

The Oracle FLOAT data type is the subtype of the NUMBER data type.

Synatx:

FLOAT(p)

p is precision in Binary bits.

Following formula is used to convert between binary and decimal precision: Decimal = 0.30103 * Binary

现在,根据您得到的结果,我认为您的列 (AVERAGE) 数据类型是 FLOAT(1)。 如果你需要更高的精度,那么你需要用二进制更精确的值来改变你的table。

举个例子:

CREATE TABLE TEST (
    f1 FLOAT,
    f2 FLOAT(1),
    f3 FLOAT(4),
    f4 FLOAT(7)
);

INSERT
    INTO
        TEST(
            f1,
            f2,
            f3,
            f4
        )
    VALUES(
        10 / 3,
        10 / 3,
        10 / 3,
        10 / 3
    );

select * from TEST;

输出:

db<>fiddle demo

如果您不提供任何精度,那么 Oracle 将采用最大精度(126 位 --> 十进制 37).

上例中,f1、f2、f3、f4列的数据类型为FLOAT、FLOAT(1)、FLOAT(4)、FLOAT(7)。

f1,f2 <-- (Your case),f3,f4列对应的小数位精度为37(126 * 0.30103),1 (1 * 0.30103) <--(你的情况)、2 (4 * 0.30103) 和 3 (7 * 0.30103).

因此,结论是 --> 更改您的 table 并根据您的更改 AVERAGE 列的 FLOAT 数据类型的精度要求。

干杯!!

在 Oracle 中,NUMBER 数据类型已经是浮点类型。它的不寻常之处在于它是一个以 10 为底的浮点数类型,因此可以安全地用于涉及金钱的计算,但它仍然是一个浮点数类型。 Docs here

可以定义一个仅包含整数的 NUMBER,方法是将子类型或特定字段定义为具有 0 的比例分量,例如

nInt_value    NUMBER(10,0);

SUBTYPE TEN_DIGIT_INTEGER_TYPE IS NUMBER(10,0);

在这种情况下,nInt_value 将只能容纳 10 位或更少的整数。

请注意,SUBTYPE 仅在 PL/SQL 中可用 - 换句话说,您不能在 PL/SQL 模块中定义 SUBTYPE,然后将其用作数据库字段。 Docs here