我有一个冗长的oracle SQL脚本,它使用了几个子查询。有没有办法可以避免重复子查询脚本,如果我想使用相同的子查询作为另一个计算的一部分,例如在下面这么小的剧本中,我可以给出' onhand_uk'子查询别名所以我只能在' running_stock_UK'中使用别名。子查询?
select distinct
trunc(al.date_required) date_allocated,
al.component_part, al.qty_required,
sum(al.qty_required) over (partition by al.component_part order by trunc(al.date_required), al.component_part) running_demand_UK,
(select sum(pl.qty_onhand)
from part_loc pl
where al.component_part = pl.part_no and pl.plant in ('W','2') and pl.location_type = 'IN') onhand_UK,
(select sum(pl.qty_onhand)
from part_loc pl
where al.component_part = pl.part_no and pl.plant in ('W','2') and pl.location_type = 'IN') - sum(al.qty_required) over (partition by al.component_part order by trunc(al.date_required),
al.component_part) running_stock_UK
from
allocations al, part_description pd
where
al.alloc_plant = 'W'
and al.status_code between '4' and '8'
and al.component_part like 'Y%'
and al.component_part = 'Y450569'
and al.component_part = pd.part_no
and substr(pd.prodtyp,1,2) in ('JC','KT','TR')
order by
al.component_part, trunc(al.date_required)
非常感谢你的帮助。
答案 0 :(得分:1)
就像Dan Bracuk一样,我虽然你也在寻找WITH
statement,但我已经看过你的查询了,在这种情况下我只想把所有东西都移到子查询中,然后拉出减法主查询:
select
x.date_allocated,
x.component_part,
x.qty_required,
x.running_demand_UK,
x.onhand_UK,
x.running_demand_UK - x.onhand_UK as running_stock_UK
from
(select distinct
trunc(al.date_required) date_allocated,
al.component_part, al.qty_required,
sum(al.qty_required) over (
partition by al.component_part
order by trunc(al.date_required), al.component_part) running_demand_UK,
(select sum(pl.qty_onhand) from part_loc pl
where al.component_part = pl.part_no
and pl.plant in ('W','2')
and pl.location_type = 'IN') onhand_UK
from allocations al, part_description pd
where al.alloc_plant = 'W'
and al.status_code between '4' and '8'
and al.component_part like 'Y%'
and al.component_part = 'Y450569'
and al.component_part = pd.part_no
and substr(pd.prodtyp,1,2) in ('JC','KT','TR') ) x
order by
x.component_part,
x.date_allocated