在SELECT语句内的CASE中重构SELECT的重复

时间:2019-09-10 20:08:34

标签: sql postgresql

如何重构此select语句以消除重复

select
    (
      case
      when (
        select my_product_int_attribute -- duplication
        from app_public.products
        where product_id = entry.product_id
      ) > 0 then 1
      when (
        select my_product_int_attribute -- duplication
        from app_public.products
        where product_id = entry.product_id
      ) = 0 then 0
      else null
      end
    )
from app_public.entries as entry
where entry.project_id = 1;

是否存在没有联接的简单选项,例如可以在select内使用的with语句之类的东西?

N.B。

项目有很多条目,条目有一个产品

2 个答案:

答案 0 :(得分:2)

可以改用CTE吗?

;with products as (
select products.product_id, products.my_product_int_attribute 
    from app_public.products
    group by products.product_id, products.my_product_int_attribute 
)
select
(
  case
  when products.my_product_int_attribute > 0 then 1
  when products.my_product_int_attribute = 0 then 0
  else null
  end
)
from app_public.entries as entry
left join products on products.product_id = entry.product_id
where entry.project_id = 1;

答案 1 :(得分:1)

您可以使用select t2.ShipDate, (select FiscalPeriod from t1 where t2.ShipDate between StartDate and EndDate) as FiscalPeriod from t2

sign()

但是, nullif(sign( (select p.my_product_int_attribute from app_public.products p where p.product_id = entry.product_id ) ), -1 ) (例如sgeddes(现已删除)答案)似乎是正确的方法。