SQL选择非零参数的记录

时间:2014-08-27 07:23:27

标签: sql postgresql

我遇到了这个SQL查询的问题:

SELECT relname, cast(n_tup_ins AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) AS ins_pct, 
                cast(n_tup_upd AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) AS upd_pct, 
                cast(n_tup_del AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) AS del_pct
FROM pg_stat_user_tables
ORDER BY relname;

此查询获取PostgreSQL基础中每个表的INSERT / UPDATE / DELETE操作的特征。这是很大的基础和许多表 (n_tup_ins + n_tup_upd + n_tup_del)= 0 。我试图通过设置 WHERE expr IS NOT NULL 来检测它,但它仍然显示错误:“除以零”。任何想法如何重建此查询以选择(n_tup_ins + n_tup_upd + n_tup_del)的非零和的记录?

2 个答案:

答案 0 :(得分:1)

您可以使用case-expression

SELECT relname, 
case 
  when (n_tup_ins + n_tup_upd + n_tup_del) > 0 then
    cast(n_tup_ins AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) 
  else 
    null 
end AS ins_pct 
FROM pg_stat_user_tables WHERE ins_pct is not null
ORDER BY relname;

答案 1 :(得分:0)

SELECT relname, 
CASE WHEN (n_tup_ins + n_tup_upd + n_tup_del) > 0 THEN cast(n_tup_ins AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) ELSE 0 END AS ins_pct,
CASE WHEN (n_tup_ins + n_tup_upd + n_tup_del) > 0 THEN cast(n_tup_upd AS numeric) / (n_tup_ins + n_tup_upd + n_tup_del) ELSE 0 END AS upd_pct,
CASE WHEN (n_tup_ins + n_tup_upd + n_tup_del) > 0 THEN cast(n_tup_upd AS numeric) / (n_tup_del + n_tup_upd + n_tup_del) ELSE 0 END AS upd_pct
FROM pg_stat_user_tables
ORDER BY relname;