如何重构此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。
项目有很多条目,条目有一个产品
答案 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(现已删除)答案)似乎是正确的方法。