截断表后,PostgreSQL错误22012由零划分

时间:2016-01-15 08:25:42

标签: mysql sql-server postgresql

所以在我截断我的表后,这个以前工作的查询现在不起作用了。即使我已经填满了我的桌子,它仍然无效。 这是我的postgreSQL代码:

SELECT 
                     k.reviewer                                               AS namareviewer
                     , COUNT(k.formcode)                                        AS actual
                     , ROUND((0.2*COUNT(k.formcode)))                           AS target
                     , SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END) AS blibli
                     , COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END) AS solusi
                     , ROUND(((COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END)+ SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END)) /ROUND((0.2*COUNT(k.formcode))))*100,2) as Percentage
                  FROM kpi k

                 GROUP
                    BY k.reviewer

我的KPI表 enter image description here

该数据与查询已经工作的第一个数据相同。为什么在第一个表被截断后出现错误SQL状态:22012偏离零?谢谢你的高级:D

1 个答案:

答案 0 :(得分:0)

使用NULLIF避免除以零错误

....
, ROUND(((COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END)+ SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END))
   /NULLIF(ROUND((0.2*COUNT(k.formcode))))*100,2) ,0) as Percentage
........

完整代码:

SELECT
  k.reviewer AS namareviewer,
  COUNT(k.formcode) AS actual,
  ROUND((0.2 * COUNT(k.formcode))) AS target,
  SUM(CASE
    WHEN k.blibliknowledge != '' THEN 1
    ELSE 0
  END) AS blibli,
  COUNT(CASE
    WHEN k.solusi != '' THEN 'foo'
    ELSE NULL
  END) AS solusi,
  ROUND(((COUNT(CASE
    WHEN k.solusi != '' THEN 'foo'
    ELSE NULL
  END) + SUM(
  CASE
    WHEN
      k.blibliknowledge != '' THEN 1
    ELSE 0
  END)) / NULLIF(ROUND((
  0.2 * COUNT(k.formcode))), 0)) * 100, 2) AS Percentage
FROM kpi k
GROUP BY k.reviewer