在同一行中重用计算字段值 - SQL

时间:2014-04-28 14:48:29

标签: sql oracle subquery oracle-sqldeveloper correlated-subquery

我要做的是编写一个提供以下输出的查询:

Output of query

帐号的日值是一个计算字段,用于计算当前在数据库中的信息的数字。然后在第+1天我需要用日值开始计算。但是我怎样才能传递这个值,以便我可以在第+1天使用它进行计算?我怎样才能做到这一点?他们不喜欢我工作场所的pl sql,这是最糟糕的情况。

目前我编写了查询以获取所有16个帐户的信息仅一天:

 select OBforeachaccount.accountnumber accountnumbers, (OBforeachaccount.OB - NVL(IDforeachaccount.sumamounts,0) - NVL(paymentsforeachaccount.sumpayments,0)) as day1, day1+5 as day2
    from
    --ophalen van CB day -1
    (select account_id accountnumber,cal_date,cb_amount_default OB from fillinggaps g, dim_date d
    where g.balance_date = d.cal_date and
    d.cal_date = TO_CHAR(sysdate -1,'DD/MM/YYYY')
    order by account_id, cal_date) OBforeachaccount,

    (select a.id accountnumber, cal_date, sum(AMOUNT_USD) sumamounts
    from fact_id_transaction i, dim_date d, dim_account a
    where i.value_date_id = d.id and 
    i.account_id  = a.id and 
    d.cal_date = TO_CHAR(sysdate -1,'DD/MM/YYYY')
    --future: add filter based on the account number
    group by a.id, cal_date
    order by a.id,cal_date) IDforeachaccount,

    (select ordering_account_id accountnumber,cal_date, sum(instructed_amount_default) sumpayments
    from fact_payment p, dim_date d
    where 
    p.value_date_id = d.id and
    d.cal_date = TO_CHAR(sysdate -1,'DD/MM/YYYY')
    group by ordering_account_id, cal_date
    order by ordering_account_id, cal_date) paymentsforeachaccount
    where 
    OBforeachaccount.accountnumber = IDforeachaccount.accountnumber(+) and
    OBforeachaccount.accountnumber = paymentsforeachaccount.accountnumber(+)

感谢您的建议

1 个答案:

答案 0 :(得分:0)

我建议使用内联视图来获取帐号和第一天的值,然后在包含的查询中,根据需要在其他列中引用第一天的值。

在伪查询中:

select
    account_number,
    day1,
    day1+x day2,
    day1+y day3
from
    (select
        account_number,
        intensive_calculation day1
    from
        tables
    where
        something = something);