避免将空值计算到嵌套的SQL查询中

时间:2019-01-18 00:30:26

标签: postgresql nested case

我有一个计算roi的PostgreSQL计算,其中定义了select 100 * ((SUM(time_product)/SUM(rt_id_count))*SUM(rental_cost))/SUM(sale_count)的几个值并使用case语句作为嵌套查询来计算。但是,如果任何值都是空的(例如缺少项rental_cost,则它将roi计算为zero,并且零值将被累加到平均值中进行计算,使平均值向下倾斜。如何在总计算中将这些零视为空?

(我取出了一些嵌套查询,并在问题中用[calculation]替换了它们;这主要是因为这是一个很长的查询,我想过滤掉噪音并使整个结构更加可见)

  (select 100 * ((SUM(time_product)/SUM(rt_id_count))*SUM(rental_cost))/SUM(sale_count)  FROM

  (select p2.id, p2.inventory_type, p2.working_value, COUNT(distinct p2.id),

  ----nested values calculated here
   (case p2.inventory_type 
      when 'set' then 
      [calculation A]
    else [calculation B] end) rental_cost,
    (case p2.inventory_type 
      when 'set' then 
      [caluculation A]
    else [calculation B]  end)   sale_count,
    (case p2.inventory_type 
      when 'set' then count(distinct rt.id)
      else 1 end 
      ) rt_id_count,
    (case p2.inventory_type 
      when 'set' then 
      [calculation ]  end)   time_total,
 [calculation]  time_product

  FROM warehouses w
    LEFT JOIN rfid_tags rt ON w.id = rt.location_id AND rt.location_type = 'Warehouse'
    LEFT JOIN products p2 ON rt.ancestor_product_id = p2.id 
    LEFT JOIN category_assignments ca  ON ca.product_id = p2.id
    LEFT JOIN categories c ON ca.category_id = c.id
    LEFT JOIN product_selections ps ON ps.rfid_tag_id = rt.id 

    WHERE 
      c.id=categories.id AND ca.primary = true  AND w.id=warehouses.id
      AND (select count(ps.id) from product_selections ps where ps.rfid_tag_id=rt.id)>0
      and p2.working_value>0 
    AND rt.location_id=w.id
    group by p2.id, p2.inventory_type, p2.working_value, c.sale_price_percentage, c.rental_price_percentage) Z) roi

1 个答案:

答案 0 :(得分:1)

如果两个参数相等,请使用NULLIF返回NULL

SELECT NULLIF(?, 0);

其中?是您的计算。

对于您的情况,这意味着:

select nullif(100 * ((SUM(time_product)/SUM(rt_id_count))*SUM(rental_cost))/SUM(sale_count), 0)
from ...