2014-09-22 158 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

相關問題