2014-09-22 87 views
1

我有一个冗长的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

你的谷歌搜索字符串是,“甲骨文与条款” – 2014-09-22 12:17:43

+0

[坏习惯踢:使用旧样式的JOIN(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10 /08/bad-habits-to-kick-using-old-style-joins.aspx) - 旧式*表格样式的逗号分隔列表被替换为ANSI中的* proper * ANSI'JOIN'语法 - ** 92 ** SQL标准(**超过20年**前),其使用不鼓励 – 2014-09-22 13:52:15

回答

1

和Dan Bracuk一样,虽然你也在寻找WITH statement,但我查看了你的查询,在这种情况下,我只是将所有东西都移到子查询中,然后将减法运算放到main查询:

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 
+0

辉煌......已将我的200多行脚本减半 - 现在更容易创建额外的子查询计算。谢谢 !!! – SMORF 2014-09-22 12:33:30

相关问题