gpt4 book ai didi

sql - 为什么 MS-SQL-Server(所有版本)将 1.0/12.0 转换为 numeric(8,6)?

转载 作者:行者123 更新时间:2023-12-03 02:08:01 25 4
gpt4 key购买 nike

我正在尝试解释 101.10 的值差异。

303'300'000/12 约为 25'275'000。
然而,根据 MS-SQL,它是 25'274'898.90。

考虑这个(简化的)SQL 语句:

SELECT 
303300000.00/12.0 AS a
,1.0/12.0*303300000.00 AS b
,1.0/12.0 AS omg
,1.0/CAST(12.0 AS float) AS expected
,0.083333*303300000.0 AS r1
,0.083333333333333300 * 303300000.0 AS r2

astounding results

我想自从我写了 1.0/12.0 以来它就会转换为 float
(这本身很愚蠢,但那是另一个故事),
但显然,它是十进制(8,6)

CREATE VIEW dbo._Test
AS
SELECT 1.0/12.0 as xxx



SELECT
COLUMN_NAME
,DATA_TYPE
,NUMERIC_PRECISION
,NUMERIC_SCALE
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '_Test'


DROP VIEW dbo._Test

这种疯狂有什么理由吗?
它是如何确定精度的?
是否有任何符号可以强制 float ,而不需要强制转换语句?

如果我在 PostgreSQL 上运行相同的查询,pg 会做对......

postgre does it right

最佳答案

文档中对此进行了解释:Precision, scale, and Length (Transact-SQL)

具体指出:

The operand expressions are denoted as expression e1, with precision p1 and scale s1, and expression e2, with precision p2 and scale s2. The precision and scale for any expression that is not decimal is the precision and scale defined for the data type of the expression.

Operation     Result precision                        Result scale *
e1 + e2 max(s1, s2) + max(p1-s1, p2-s2) + 1 max(s1, s2)
e1 - e2 max(s1, s2) + max(p1-s1, p2-s2) + 1 max(s1, s2)
e1 * e2 p1 + p2 + 1 s1 + s2
e1 / e2 p1 - s1 + s2 + max(6, s1 + p2 + 1) max(6, s1 + p2 + 1)

这里最重要的部分是最后一个。就您而言,您有一个 decimal(2,1) 和一个 decimal(3,1)。为了精度,这会导致:

 2 - 1 + 1 + max(6,1 + 3 + 1) = 2 + max(6,5) = 2 + 6 = 8

对于规模,我们得到:

max(6,1+3+1) = max(6,5) = 6

获取结果值,您将得到一个十进制(8,6)

关于sql - 为什么 MS-SQL-Server(所有版本)将 1.0/12.0 转换为 numeric(8,6)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51787973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com