Postgresql查询结果除以0后使用案例检查0

时间:2016-11-29 19:46:28

标签: postgresql amazon-redshift

以下查询使用子查询来允许计算加权值。我收到的问题是0错误,它随机发生,对于真正的0值聚合以及从子查询中可能的> 0聚合返回。

SELECT
  table1.id,
  SUM(subquery1.total_value_1),
  CASE
  WHEN SUM(subquery1.total_value_1) = 0 THEN 0
  ELSE ROUND(SUM(percentage_value * (table1.value_1 /subquery1.total_value_1 ::FLOAT)) ::NUMERIC,2)
  END AS percentage_value
FROM
    table1,
    (SELECT
        id,
        SUM(value_1) AS total_value_1
    FROM
        table1
    WHERE
        report_time BETWEEN '2016-10-28 00:00' AND '2016-10-29 23:59'
    GROUP BY
        id
    ) subquery1
WHERE
  table1.id = subquery1.id
  AND report_time BETWEEN '2016-10-28 00:00' AND '2016-10-29 23:59'
  AND table1.id = 12572
GROUP BY
  table1.id
ORDER BY
  table1.id

在某些情况下,尽管subquery1.total_value_1的值为0,但Case语句仍在对除法进行评估。请注意,subquery1.total_value_1不可能为NULL,因为表默认此值为如果未定义添加值,则插入0。

1 个答案:

答案 0 :(得分:0)

在下面的示例中,两行的sum(列)为1,而column等于零或一:

a=# with v as (
  select generate_series(0,1,1) al
) 
select sum(v.al) over(),v.al 
from v;
 sum | al
-----+----
   1 |  0
   1 |  1
(2 rows)

所以在你的SUM(subquery1.total_value_1) = 0中,subquery1.total_value_1 ::FLOAT可能不等于零,但division by zero会是IDependency,这样你得interface IDependency { a(): number; b(): string; }