PostgreSQL 数字字段溢出错误 - 精度为 10、小数位数为 1 的字段必须四舍五入为小于 10^9 的绝对值

PostgreSQL Numeric Field Overflow Error - A field with precision 10, scale 1 must round to an absolute value less than 10^9

我正在尝试找出每行中 imls2016.visits 和 imls2010.visits 的两个值之和之间的百分比差异。在我在联合声明中添加第三个 table(table 为 imls_regions)之前,它之前工作正常。但是任何时候我 运行 新代码都会抛出一个数字溢出错误。我已经调整了精度和比例,但我无法纠正这个错误。请问我应该在我的代码中更改什么: (PostgreSQL 12)

我的代码:

SELECT imlsreg.obereg,
        imlsreg.obereg_name,
        SUM(imls2016.visits) AS total_visits_2016,
        SUM(imls2010.visits) AS total_visits_2010,
        ROUND((CAST(SUM(imls2016.visits) AS decimal(10, 1)) - SUM(imls2010.visits)) / SUM(imls2010.visits) * 100, 1) AS pct_change_in_visits
FROM imls_regions AS imlsreg INNER JOIN imls_library_survey_2016 AS imls2016
ON imlsreg.obereg = imls2016.obereg
INNER JOIN imls_library_survey_2010 AS imls2010
ON imlsreg.obereg = imls2010.obereg
WHERE imls2016.visits >= 0 AND imls2010.visits >= 0
GROUP BY imlsreg.obereg, imlsreg.obereg_name
ORDER BY pct_change_in_visits ASC;

当您强制转换为 decimal(10,1) 时,您正在缩小 SUM(imls2016.visits) 的允许值范围以换取更高的精度,但这会导致结果溢出。

您可以做两件事:

  1. 在计算 SUM(imls2016.visits) - SUM(imls2010.visits)
  2. 之后 执行转换
  3. 降低转换精度。

实施第一个可能就足够了,您可以将 pct_change_in_visits 定义为:

ROUND(CAST(SUM(imls2016.visits) - SUM(imls2010.visits) AS decimal(10, 1)) / SUM(imls2010.visits) * 100, 1) AS pct_change_in_visits

好的,我找到问题了。我的总和值的精度超过 10(这意味着当总和仍为整数格式时,其长度为 12 个值)因此在转换时会抛出数字字段溢出错误。为了找出我哪里出错了,我删除了清单 1.1 中的 ROUND() 和 CAST() 函数:

  • 清单 1.1:
SELECT imlsreg.obereg,
        imlsreg.obereg_name,
        SUM(imls2016.visits) AS total_visits_2016,
        SUM(imls2010.visits) AS total_visits_2010,
        (SUM(imls2016.visits) - SUM(imls2010.visits)) / SUM(imls2010.visits) * 100 AS pct_change_in_visits
FROM imls_regions AS imlsreg INNER JOIN imls_library_survey_2016 AS imls2016
ON imlsreg.obereg = imls2016.obereg
INNER JOIN imls_library_survey_2010 AS imls2010
ON imlsreg.obereg = imls2010.obereg
WHERE imls2016.visits >= 0 AND imls2010.visits >= 0
GROUP BY imlsreg.obereg, imlsreg.obereg_name
ORDER BY pct_change_in_visits ASC;

这给了我我想看到的访问总和,但暂时忽略 pct_change(大多数 pct_change 是 0,因为 sql 中的两个整数相除得到一个整数因此将操作值转换为十进制或双精度数字数据类型很重要)

在计算最大访问值的长度(长度为 12)后,我能够找到准确的精度值。然后我恢复到我以前的代码并将精度调整为数字 (14, 1)。见清单 1.2 中的代码:

  • 清单 1.2:
SELECT imlsreg.obereg,
        imlsreg.obereg_name,
        SUM(imls2016.visits) AS total_visits_2016,
        SUM(imls2010.visits) AS total_visits_2010,
        ROUND((CAST(SUM(imls2016.visits) AS decimal(14, 1)) - SUM(imls2010.visits)) / SUM(imls2010.visits) * 100, 2) AS pct_change_in_visits
FROM imls_regions AS imlsreg INNER JOIN imls_library_survey_2016 AS imls2016
ON imlsreg.obereg = imls2016.obereg
INNER JOIN imls_library_survey_2010 AS imls2010
ON imlsreg.obereg = imls2010.obereg
WHERE imls2016.visits >= 0 AND imls2010.visits >= 0
GROUP BY imlsreg.obereg, imlsreg.obereg_name
ORDER BY pct_change_in_visits ASC;