2014-10-06 40 views
-1

目前我有PLSQL代码来处理和计算数据。但问题是,这可以在没有PLSQL的情况下完成,即使用Oracle分析函数?如何比较Oracle的同一表中的行

表中包含的数据计划快照和实际值如下:

data_snap_id actual_dt planned_dt amount 
------------ --------- --------- ------ 
1       2014-10-01 20.00 
1       2014-10-02 10.00 
1       2014-10-03 5.00 
1       2014-10-04 10.00 
1       2014-10-05 51.00 
1       2014-10-06 10.00 
1       2014-10-07 50.00 
1       2014-10-08 15.00 
1       2014-10-09 55.00 
1       2014-10-10 100.00 
2    2014-10-01 2014-10-01 25.00 
2    2014-10-02 2014-10-02 5.00 
2    2014-10-03 2014-10-03 15.00 
2    2014-10-04 2014-10-04 15.00 
2    2014-10-05 2014-10-05 5.00 
2       2014-10-06 10.00 
2       2014-10-07 50.00 
2       2014-10-08 15.00 
2       2014-10-09 55.00 
2       2014-10-10 10.00 

和预期的查询输出如下:

action_date planned_amount actual_amount adds deletes 
----------- -------------- ------------- ---- ------- 
2014-10-01 20.00   25.00   5.00 0.00 
2014-10-02 10.00   5.00   0.00 5.00 
2014-10-03 5.00   15.00   10.00 0.00 
2014-10-04 10.00   15.00   5.00 0.00 
2014-10-05 51.00   5.00   0.00 46.00 
2014-10-06 5.00       0.00 0.00 
2014-10-07 50.00       0.00 0.00 
2014-10-08 15.00       0.00 0.00 
2014-10-09 55.00       0.00 0.00 
2014-10-10 100.00       0.00 90.00 

回答

2

假设我正确理解你的问题,你可以使用聚合使用maxcase查询来分隔您的计划金额和实际金额,然后使用子查询来获取您的增加和删除:

select action_date, 
    planned_amount, 
    actual_amount, 
    case when actual_amount-planned_amount < 0 
     then 0 else actual_amount-planned_amount end adds, 
    case when planned_amount-actual_amount < 0 
     then 0 else planned_amount-actual_amount end deletes 
from (
    select planned_dt action_date, 
     coalesce(max(case when actual_dt is null then amount end),0) planned_amount, 
     coalesce(max(case when actual_dt is not null then amount end),0) actual_amount 
    from yourtable 
    group by planned_dt 
) t 
order by action_date